Reputation: 3
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?
Upvotes: 0
Views: 6513
Reputation: 780994
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);
Upvotes: 4
Reputation: 3440
const mappedFruits = fruits.map(fruit => {
return {
...fruit,
isFavorite: true,
attributes: attributes.map(attribute => {
return {
...attribute,
isFavorite: true,
}
})
}
})
Upvotes: 1