Search code examples
javascriptarraysnestedarray.prototype.map

How to change a value in nested array


Code:

let fruits = [{
    name: 'apple',
    attributes: [{
        type: 'Granny Smith',
        color: 'green',
        isFavorite: true
      },
      {
        type: 'Ambrosia',
        color: 'red',
        isFavorite: true
      }
    ],
    isFavorite: true
  },
  {
    name: 'Pear',
    attributes: [{
        type: 'Asian',
        color: 'brown',
        isFavorite: true
      },
      {
        type: 'White Pear',
        color: 'white',
        isFavorite: false
      }
    ],
    isFavorite: true
  },
]

const fruitChecked = fruits.map(fruit => {
  return { ...fruit,
    isFavorite: true
  }
})

const fruitAttributesChecked = fruitChecked.map(fruit => {


  (fruit.attributes).map(attr => {
    return { ...attr,
      isFavorite: true
    }

  })
})

console.log(fruits)
console.log(fruitChecked)
console.log(fruitAttributesChecked)

I am trying to change ALL the isFavorite value to true within each object and the isFavorite value within attributes to true.

However I'm getting something similar to this for [undefined,undefined] for fruitAttributesChecked

The outcome I desire is below for fruitAttributesChecked

fruitAttributesChecked =
[
   {name: 'apple', 
    attributes: [
          {type: 'Granny Smith', color:'green', isFavorite: true},
          {type: 'Ambrosia', color:'red', isFavorite: true}
    ], 
     isFavorite: true
   },
   {name: 'Pear', 
    attributes: [
          {type: 'Asian', color:'brown', isFavorite: true},
          {type: 'White Pear', color:'white', isFavorite: false}
    ], 
     isFavorite: true
   },
]

What am I missing here?


Solution

  • You can use a nested map() to return a modified attributes array in the object.

    let fruits = [{
        name: 'apple',
        attributes: [{
            type: 'Granny Smith',
            color: 'green',
            isFavorite: true
          },
          {
            type: 'Ambrosia',
            color: 'red',
            isFavorite: true
          }
        ],
        isFavorite: true
      },
      {
        name: 'Pear',
        attributes: [{
            type: 'Asian',
            color: 'brown',
            isFavorite: true
          },
          {
            type: 'White Pear',
            color: 'white',
            isFavorite: false
          }
        ],
        isFavorite: true
      },
    ]
    
    const fruitChecked = fruits.map(fruit => ({ ...fruit,
      isFavorite: true,
      attributes: fruit.attributes.map(attribute => ({ ...attribute,
        isFavorite: true
      }))
    }))
    
    console.log(fruitChecked);