提问人:Javascript Learner 提问时间:7/14/2023 最后编辑:Mike 'Pomax' KamermansJavascript Learner 更新时间:7/14/2023 访问量:60
在数组对象中,如何仅更改第二级的值
In an array object how to change only value on second level
问:
我有一个数组对象,我想仅在第二级(名称为梨)中将 isFavorite 的值更改为 true,我尝试了地图函数,但这在每个级别上都在更改值,我在下面编写了该函数,任何人都可以看看它有什么问题吗?
功能
const fruitChecked = fruits.map((fruit) => ({
...fruit,
attributes: fruit[1].attributes.map((attribute) => ({
...attribute,
isFavorite: true,
})),
}));
数组示例
[
{
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 },
],
},
];
我尝试了我提到的功能,也提到了我正在尝试的 dat。我使用了地图,但这并没有给我结果。
答:
0赞
Carsten Massmann
7/14/2023
#1
也许这就是你所追求的?
const fruits=[
{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}
],
}
];
fruits[1].attributes.forEach(a=>a.isFavorite=true);
console.log(fruits);
0赞
James
7/14/2023
#2
在地图中,在更改属性之前,您需要检查水果名称是否为 Pear:
const fruits = [
{
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 },
],
},
];
const adjustedFruits = fruits.map(fruit => ({
...fruit,
attributes: fruit.name === "Pear"
? fruit.attributes.map(att => ({
...att,
isFavorite: true
}))
: fruit.attributes
}));
console.log(adjustedFruits);
评论
0赞
Javascript Learner
7/14/2023
当我想更改所有属性值时使用它,如果我只想更改 1 个值或两个值怎么办?
0赞
James
7/14/2023
与使用三元组设置的方式类似,例如,如果您想检查类型,您可以在设置时执行类似的事情。attributes
isFavorite
评论
attributes: fruit[1].attributes.map(...)
attributes: fruit.attributes.map(...)
.map()
.map()