[英]How to set value to a property in a Javascript object, which is identified by an array of keys
If there is a Javascript object with multiple levels, as in: 如果存在一个具有多个级别的Javascript对象,例如:
myObject = {
a: 12,
obj11: {
obj111: 'John',
b:13,
obj1111: { a:15,
b: 35 }
obj21: {
a:15,
b:16 }
}
I want to write a function to which is passed the object, an array of keys and the value to be assigned to the matched property. 我想编写一个函数,将对象,键数组和要分配给match属性的值传递给该函数。
function myFunc (myObj,myArr, newValue) {
...
}
myFunc(myObject, ['obj11', 'obj1111'], {z:12});
console.log(myObject.obj11.obj1111);
Should display {z:12}. 应该显示{z:12}。 Assume that the keys in the array are always correct.
假设数组中的键始终正确。
You can use reduce()
method to find nested object and if its found then you can use Object.assign()
to add new property. 您可以使用
reduce()
方法查找嵌套对象,如果找到了嵌套对象,则可以使用Object.assign()
添加新属性。
var myObject = {"a":12,"obj11":{"obj111":"John","b":13,"obj1111":{"a":15,"b":35},"obj21":{"a":15,"b":16}}} function myFunc (myObj, myArr, newValue) { myArr.reduce(function(r, e, i, arr) { if(!arr[i+1] && typeof r[e] == 'object') Object.assign(r[e], newValue); return r[e] || {} }, myObj) } myFunc(myObject, ['obj11', 'obj1111'], {z:12}); console.log(myObject)
Update If you just want to change value of nested property then you can use something like this. 更新如果您只想更改嵌套属性的值,则可以使用类似这样的东西。
var myObject = {"a":12,"obj11":{"obj111":"John","b":13,"obj1111":{"a":15,"b":35},"obj21":{"a":15,"b":16}}} function myFunc (myObj, myArr, newValue) { myArr.reduce(function(r, e, i, arr) { if(!arr[i+1] && r[e]) r[e] = newValue return r[e] || {} }, myObj) } myFunc(myObject, ['obj11', 'obj1111'], {z:12}); console.log(myObject)
function myFunc(myObj,myArr,newValue){
var temp=myObj;
for(var I=0;I<myArr.length;I++){
temp=temp[myArr[I]];
}
temp=newValue;
};
Update : This is a classic example of how you can access properties from an object in JavaScript. 更新 :这是如何从JavaScript中的对象访问属性的经典示例。 You may, for simplicity, consider object as an array of properties.
为简单起见,您可以将对象视为属性数组。 Now try and access the required property as if it is the index of the array.
现在尝试访问所需属性,就好像它是数组的索引一样。 If u have a nested object, consider it as a nested array.
如果您有一个嵌套对象,请将其视为嵌套数组。
Eg: console.log(myObj['obj11']['obj1111']); 例如:console.log(myObj ['obj11'] ['obj1111']);
The above code will display { a:15, b: 35 }, before running the myFunc() and will display {z:12} after running it. 上面的代码将在运行myFunc() 之前显示{a:15,b:35},并在运行后显示{z:12}。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.