如何在键值对对象(jsx)中添加到列表中



如果您有一个键值对

let appleLocations = [{
"red": [],
"blue": [],
"green": []
}
]

您可以找到它们所在的位置(简单的数字标识符(,并希望键/值最终(在您完成搜索后,每次向列表中添加1个数字标识符(如下:

appleLocations = [
"red": [2,4,6],
"blue": [3,7,9,8],
"green": [0,5]
]

问题变成了——如何在不必首先引用数组的情况下将数组添加到最初的空白数组和随后填充的数组中。

appleLocations["red"] = [appleLocations["red"], newLocationNumber]

每次运行时返回一个带有子列表和更多子列表的列表,类似于。。。[2,[4,[6]

在哪里更有用[2,4,6]

因为它不是";命名为";数组,不能使用concat或其他有用的操作。

这里基本上有两种选择。保留您的原始语法并访问数组中的单个元素,以获得您想要更改的属性:

let appleLocations = [{
"red": [],
"blue": [],
"green": []
}
];

appleLocations[0].red = appleLocations[0].red.concat(2);
console.log(appleLocations[0].red);
console.log(appleLocations);

或者,将第二个语法修改为对象的正确语法,然后像往常一样访问属性。我在这里使用排列语法只是为了展示向数组添加元素的其他方法:

let appleLocations = {
"red": [2,4,6],
"blue": [3,7,9,8],
"green": [0,5]
};
// A different syntax just to show what's possible
appleLocations = {
...appleLocations,
red: [...appleLocations.red, 10],
};
console.log(appleLocations.red);
console.log(appleLocations);

Yo可以对数组使用flat((函数

最新更新