Search code examples
javascriptarraysobject-literal

How to dynamically add an object with an array key to an object literal?


I have an existing 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."}
]
}

];

I'm trying to add more objects dynamically as follows:

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

I have tried various options at -???- but nothing works. Advice gratefully received.


Solution

  • Why not take the complete object for pushing and a mapping of nextwordSentencesArray with the wanted properties?

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