[英]How to set JavaScript object's property value?
I have a JavaScript object that looks something like this: 我有一个JavaScript对象,看起来像这样:
obj = {
person: {
male: true,
age: 10
},
state: {
quit: false,
rain: -3
},
game: {
settings: {
lang: 'en',
os: 'win',
ver: 10,
},
},
next: 55,
last: 10,
};
I'd like to create a function that can be used to set any of the obj's values like this: 我想创建一个可用于设置obj值的函数,如下所示:
function updateObj( property /*: string[]*/, value /*: any*/ ) {
obj[property[0]][property[1]] = value; <-- How to generalize?
}
So then I can do things like: 因此,我可以执行以下操作:
updateObj( ['person', 'male'], false );
updateObj( ['state', 'rain'], 19 );
However the current implementation won't work properly if the property parameter length is not equal to 2. How can this line of code: 但是,如果属性参数长度不等于2,当前的实现将无法正常工作。这行代码如何:
obj[property[0]][property[1]] = value;
be generalized to work with any array size of property? 可以与属性的任何数组大小一起使用?
Below method will achieve your result, used reduceRight below 下面的方法将达到您的结果,下面使用reduceRight
// with reduceRight
function updateObj(prop, value) {
prop = prop.reverse()
prop.reduceRight((o, d, i) => i == 0 ? (o[d] = value): o[d] , obj)
}
// with Reduce (efficient than above)
function updateObj(prop, value) {
prop.reduce((o, d, i) => i == prop.length -1 ? (o[d] = value): o[d] , obj)
}
updateObj( ['person', 'male'], false );
updateObj( ['state', 'rain'], 19 );
Iterate over the property parts and for each one get the nested object: 遍历属性部分,并为每个属性部分嵌套对象:
function updateObj( property /*: string[]*/, value /*: any*/ ) {
var base = obj;
for (var i = 0; i < property.length - 1; i++) {
base = base[property[i]];
}
base[property[property.length - 1]] = value;
}
You could save the last key and reduce the object by taking the keys and return the last object reference. 您可以保存最后一个键并通过获取键来减少对象并返回最后一个对象引用。 For not given properties assign an empty object.
对于未给定的属性,请分配一个空对象。
At the end take the last key and assign the value. 最后,使用最后一个键并分配值。
function updateObj(properties, value) { var last = properties.pop(); properties.reduce((o, k) => o[k] = o[k] || {}, obj)[last] = value; } var obj = { person: { male: true, age: 10 }, state: { quit: false, rain: -3 }, game: { settings: { lang: 'en', os: 'win', ver: 10 }, }, next: 55, last: 10 }; updateObj(['person', 'male'], false); updateObj(['state', 'rain'], 19); updateObj(['banana', 'ware'], 'snakeoil'); console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.