I have an array object i want to change the value of isFavorite to true only in second level (where name is pear) i tried map function but that is changing value on every level and i have written that function below can anyone look what is wrong with it?
Function
const fruitChecked = fruits.map((fruit) => ({
...fruit,
attributes: fruit[1].attributes.map((attribute) => ({
...attribute,
isFavorite: true,
})),
}));
Array Example
[
{
name: "apple",
attributes: [
{ type: "Granny Smith", color: "green", isFavorite: true },
{ type: "Ambrosia", color: "red", isFavorite: false },
{ type: "Persian", color: "red", isFavorite: false },
{ type: "Asian", color: "brown", isFavorite: true },
{ type: "greek", color: "red", isFavorite: false },
],
},
{
name: "Pear",
attributes: [
{ type: "Asian", color: "brown", isFavorite: true },
{ type: "White Pear", color: "white", isFavorite: false },
{ type: "Asian", color: "brown", isFavorite: true },
{ type: "White Pear", color: "white", isFavorite: false },
],
},
];
I tried the function which i mentioned in question and also mentioned the dat with which i am trying. and i used map but that is not giving me the result“
2
Answers
Maybe this is what you are after?
In the map, you need to check if the fruit name is Pear before changing the attributes: