如何将带有数组键的对象动态添加到对象字面量?

我有一个现有的对象文字:


var words=[

    {

"word":"callous",

"definition":"uncaring",

"examples": [

   {"sentence":"How could you be so callous?"},

   {"sentence":"What a callous thing to say!"},

   {"sentence":"That showed a callous disregard for the consequences."}

]

}

];


我正在尝试动态添加更多对象,如下所示:


var obj={};

obj.word="nextword";

obj.definition ="nextword definition";

obj.examples= ???;

for (var i = 0; i < nextwordSentencesArray.length; i++) {

 ??? obj.examples.sentence.push(nextwordSentencesArray[i]);

}

words.push(obj);

我在 -???- 尝试了各种选项,但没有任何效果。感激地收到建议。


慕尼黑5688855
浏览 147回答 1
1回答

天涯尽头无女友

为什么不使用完整的对象进行推送和nextwordSentencesArray与所需属性的映射?words.push({&nbsp; &nbsp; word: "nextword",&nbsp; &nbsp; definition: "nextword definition",&nbsp; &nbsp; examples: nextwordSentencesArray.map(sentence => ({ sentence }))});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript