Shoe
Shoe

Reputation: 157

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.

Upvotes: 1

Views: 59

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386610

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

Upvotes: 4

Related Questions