如何在 javascript 数组中存储对(和 update/retrieve)对象 属性 的引用
How to store reference to (and update/retrieve) object property in javascript array
这是一个对象
var someObject = {
value1: 'nothing',
value2: 'nothing',
...
}
这是一个数组
var someArray = [someObject.value1, someObject.value2, ...]
这里有个问题
forEach(var i in someArray){
//How would I update someObject.value1 here
someArray[i] = 'something'
}
//so that this would be 'something'
var someVar = SomeObject.value1
编辑:此解决方案满足我的需求
someObject: same
someArray = ['value1', 'value2']
forEach(var i in someArray){
someObject[someArray[i] = 'something'
}
console.log(someObject.value1) //something
在 someArray
中,您引用了原始值而不是对象。
您可以存储对象的键 someObject
并使用它们来更新对象。
var someObject = { value1: 'nothing', value2: 'nothing' },
someArray = ['value1', 'value2']; // keys
someArray.forEach(k => someObject[k] = 'something'); // update with keys
console.log(someObject);
我认为您正在尝试使用数组 (someArray) 更新对象 (someObject)。如果是这种情况,你不必,因为你可以直接循环一个对象:
for(key in someObject){
someObject[key] = 'something'
}
这是一个对象
var someObject = {
value1: 'nothing',
value2: 'nothing',
...
}
这是一个数组
var someArray = [someObject.value1, someObject.value2, ...]
这里有个问题
forEach(var i in someArray){
//How would I update someObject.value1 here
someArray[i] = 'something'
}
//so that this would be 'something'
var someVar = SomeObject.value1
编辑:此解决方案满足我的需求
someObject: same
someArray = ['value1', 'value2']
forEach(var i in someArray){
someObject[someArray[i] = 'something'
}
console.log(someObject.value1) //something
在 someArray
中,您引用了原始值而不是对象。
您可以存储对象的键 someObject
并使用它们来更新对象。
var someObject = { value1: 'nothing', value2: 'nothing' },
someArray = ['value1', 'value2']; // keys
someArray.forEach(k => someObject[k] = 'something'); // update with keys
console.log(someObject);
我认为您正在尝试使用数组 (someArray) 更新对象 (someObject)。如果是这种情况,你不必,因为你可以直接循环一个对象:
for(key in someObject){
someObject[key] = 'something'
}