簡體   English   中英

如何動態地將帶有數組鍵的對象添加到對象文字?

[英]How to dynamically add an object with an array key to an 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 }))
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM