javascript - 如何将具有数组键的对象动态添加到对象文字?

标签 javascript arrays object-literal

我有一个现有的对象字面量:

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);

我在 -???- 尝试了各种选项,但没有任何效果。非常感谢您的建议。

最佳答案

为什么不采用完整的对象进行推送并将 nextwordSentencesArray 与所需属性进行映射?

words.push({
    word: "nextword",
    definition: "nextword definition",
    examples: nextwordSentencesArray.map(sentence => ({ sentence }))
});

关于javascript - 如何将具有数组键的对象动态添加到对象文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57905302/

相关文章:

c# - html:点击 href 链接后执行其他操作

javascript - Google OpenID - 如何在 javascript 中使用 checkid_immediate?

javascript - 使用回调动态加载多个远程脚本?

c# - 查找数组之间匹配项数量的最快方法是什么?

arrays - Ada:用可变大小的数组打包记录

javascript - 如何将参数传递给对象文字中的函数

javascript - 如何将键/值对添加到 JavaScript 对象的特定位置?

Javascript 'normal' 对象与模块模式

javascript - 如何将变量从路由传递到 server.js

PHP、MySQL : Problem retrieving image url strings from database