问题
Given an object obj, I can modify its properties by using something like obj.a.b.c = "new value". However, I want to be able to do this programmatically, with the property's location in the form of an array. How can I make a function that looks like this:
modifyProperty(obj, ["a", "b", "c"], "new value");
and is equivalent to
obj.a.b.c = "new value";
?
回答1:
You could use Array#reduce for it, with a default object if no object is available.
function modifyProperty(object, path, value) {
var last = path.pop();
path.reduce(function (r, a) {
if (!(a in r)) {
r[a] = {};
}
return r[a];
}, object)[last] = value;
}
var object = {};
modifyProperty(object, ["a", "b", "c"], "new value");
console.log(object);
回答2:
You can do something like this:
function modifyProperty(obj, props, val) {
var propName = props.pop();
var o = props.reduce(function(obj, p) {
return obj[p];
}, obj);
o[propName] = val;
}
var obj = {
a: {b: {c: "old value"}}
}
modifyProperty(obj, ["a", "b", "c"], "new value");
console.log(obj);
回答3:
In order to set the object values dynamically i have a code called Object.prototype.setNestedValue() This will take an array of items which designate the properties of an array and the last one is the value. Such as
Object.prototype.setNestedValue = function(...a) {
a.length > 2 ? typeof this[a[0]] === "object" && this[a[0]] !== null ? this[a[0]].setNestedValue(...a.slice(1))
: (this[a[0]] = typeof a[1] === "string" ? {} : new Array(a[1]),
this[a[0]].setNestedValue(...a.slice(1)))
: this[a[0]] = a[1];
return this;
};
var obj = {}.setNestedValue("a","b","c",100);
console.log(JSON.stringify(obj,null,2));
If instead of string arguments you use integers you get an array instead such as
Object.prototype.setNestedValue = function(...a) {
a.length > 2 ? typeof this[a[0]] === "object" && this[a[0]] !== null ? this[a[0]].setNestedValue(...a.slice(1))
: (this[a[0]] = typeof a[1] === "string" ? {} : new Array(a[1]),
this[a[0]].setNestedValue(...a.slice(1)))
: this[a[0]] = a[1];
return this;
};
var obj = {}.setNestedValue("a",2 ,3,100);
console.log(JSON.stringify(obj,null,2));
来源:https://stackoverflow.com/questions/39300465/how-to-modify-an-object-property-given-its-location-within-the-object