[英]JavaScript: Assigning values to array of null/empty objects
I know the syntax is wrong, but in the following code key
is supposed to equal the object's key. 我知道语法是错误的,但是在下面的代码中, key
应该等于对象的键。 As the loop iterates, key
gets assigned the i
value, so a:1
, b:2
...etc. 随着循环的循环, key
被分配了i
值,因此a:1
, b:2
...等。
var objArr = [
{a: null},
{b: null},
{c: null}
];
for (var i = 0; i < objArr.length; i++) {
objArr[i].key = i;
}
Assuming the objects only contain one key, you can find the key using Object.keys[0]
: 假设对象仅包含一个键,则可以使用Object.keys[0]
查找该键:
var objArr = [ {a: null}, {b: null}, {c: null} ]; objArr.forEach((obj, i) => { const key = Object.keys(obj)[0]; obj[key] = i; }); console.log(objArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.