Skip to content
Advertisement

Trying to iterate over an array of objects, and create a new property that contains an array of words from that sentence’s text property

My state contains the following property:

JavaScript

Now I am trying to iterate over the sentences, create a new property on each sentence called words which will be an array of words. When I console.log(this.sentences), I see the new property but when I try to render the property in the DOM, it doesn’t show the new property.

JavaScript

Advertisement

Answer

Array#map returns:

A new array with each element being the result of the callback function.

Also, you need to add the value computed in each iteration:

Function that is called for every element of arr. Each time callbackFn executes, the returned value is added to newArray.

Therefore, to get the updated version, you need to assign it to this.sentences:

JavaScript
JavaScript

A better way would be creating a computed property to return the list of sentences with the words in them:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement