Reputation: 2248
I want to be able to update an Object or several Objects using a function specifying the location of what I would want to update in the Obeject. I am not sure what the correct syntax for it. My attempt below actually creates a new parameter in the original object, as instead I would like to update the existing field of the User object.
var User = {
local: {
location: {
city: "",
state: ""
}
}
}
var Profile = {
location: {
city: "",
state: ""
}
}
function update(model, parameter, updatedLocation) {
return model[updatedLocation] = {
city: updatedLocation.city,
state: updatedLocation.state,
};
}
update(User, ["local"]["location"], { city: "ny", state: "ny"});
update(Profile, ["location"], { city: "ny", state: "ny"});
console.log(User);
console.log(Profile);
Upvotes: 0
Views: 133
Reputation: 6112
You could give this a try. Basically, it's a generic way to go to any level in an object and update properties. Details in the code comments
var User = {
local: {
location: {
city: "",
state: ""
}
}
}
var Profile = {
location: {
city: "",
state: ""
}
}
function update(obj, path, updatedProps) {
var objToUpdate = obj;
// Iterate down the path to find the required object
for (var i = 0; i < path.length; i++) {
if (objToUpdate[path[i]]) {
objToUpdate = objToUpdate[path[i]]
} else {
// If any path is not found, then no point continuing
objToUpdate = null;
break;
}
}
if (objToUpdate) {
var props = Object.keys(updatedProps);
for (var j = 0; j < props.length; j++) {
var prop = props[j];
objToUpdate[prop] = updatedProps[prop] || objToUpdate[prop];
}
}
return obj;
}
update(User, ["local", "location"], {
city: "ny",
state: "ny"
});
update(Profile, ["location"], {
city: "ny",
state: "ny"
});
console.log("User:", User);
console.log("Profile:", Profile);
Upvotes: 1
Reputation: 2422
Similar to the other answer here, but it doesn't require explicit coding of the location
structure:
function update(model, parameter, newVal) {
model[parameter] = newVal;
}
update(User["local"], "location", { city: "ny", state: "ny"});
update(Profile, "location", { city: "ny", state: "ny"});
Or if you're only updating location, you could simplify the function:
function updateLocation(model, newVal) {
model.location = newVal;
}
Upvotes: 0