[英]Populating Javascript-Object keys/values in loop?
I want to do something like this: 我想做这样的事情:
let obj = [];
for(let i=0;i<4;i++) {
// doing some stuff here ...
// and then, finally:
obj[i].words = wordsOfSentence;
}
However this gives me an error. 但是,这给了我一个错误。
Cannot set property 'words' of undefined
无法设置未定义的属性“单词”
For now, I solved it like this: 现在,我像这样解决它:
let obj = [{}, {}, {}, {}];
for(let i=0;i<4;i++) {
// doing some stuff here ...
// and then, finally:
obj[i].words = wordsOfSentence;
}
...but this means I have to always push an empty object into the array beforehand? ...但这意味着我必须总是总是事先将一个空对象推入数组? Whats the standard / an elegant solution here?
什么是标准/优雅的解决方案?
You must have to create a blank JSON object, before store any key-value pair and then you will push a JSON object in array. 在存储任何键值对之前,必须必须创建一个空白的JSON对象,然后才能将JSON对象压入数组。
let objects = [];
for (let i = 0; i < 4; i++) {
objects[i] = {};
objects[i].words = 'wordsOfSentence';
objects.push(objects[i]);
}
console.log(objects);
Create the object and then add it to the array: 创建对象,然后将其添加到数组中:
let obj = [];
for(let i=0;i<4;i++) {
// doing some stuff here ...
// and then, finally:
const newObj = { words: wordsOfSentence }
obj[i] = newObj;
}
You can use if statement 您可以使用if语句
if( obj[i] ){
obj[i].words = wordsOfSentence;
}
Or you can assign a default value before accessing 或者,您可以在访问之前指定默认值
obj[i] = obj[i] || {}
You can simply push a new object in each iteration. 您可以在每次迭代中简单地推送一个新对象。
let objects = [];
for (let i = 0; i < 4; i++) {
objects.push({words: wordsOfSentence});
}
let _obj = {};
_obj.words = [];
for (let i = 0; i < 4; i++) {
_obj.words.push('WordsOfSentense');
}
console.log(_obj);
This should help. 这应该有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.