javascript - 用多个键和值填充对象数组
问题描述
我在@change 上有一个接收这些值的方法。
changeAttr(id, key, value) {
const selections = [];
},
id可以是任何数字,key可以是:color、size、sex 等...,value可以是:red、8、female 等。在第一次接收中,值可以是例如:
id = 3
、用户选择另一个选项。例如: , ,或 , , ...等key = "color"
value = "red"
id = 3
key = "sex"
value = "female"
id = 5
key = "size"
value = "50"
例如,我想以这种方式动态填充对象数组。
selections = [{
"3": {
"color": "red",
"sex": "male",
"size": "40"
},
{
"5": {
"color": "black",
"sex": "female",
"size": "36"
},
{
"8":{
"color": "black",
"sex": "female",
"size": "36"
...
},
...
}];
如果相同id的键已经存在,我想覆盖这些值。如果它不存在,则必须为其 id 添加它。
我希望我已经解释清楚了。非常感谢您的宝贵时间
解决方案
您可以简单地使用数组语法:
考虑到
let yourObject = {}
您可以使用 [] 来定义一个属性
yourObject["color"] = "red"
因此,按照您的逻辑,您可以执行以下操作:
yourObject[key] = value
提示:使用 int 字符串作为索引并不是一个很好的做法,因为 JS 会重新索引数组,我建议你像这样构造你的对象:
[
{
id: 3
color: "red",
sex: "male",
size: "40"
},
{
id: 5,
color: "black",
sex: "female",
size: "36"
},
{
id: 8,
color: "black",
sex: "female",
size: "36"
},
...
];
编辑 :
const selections = [];
function changeAttr(id, key, value) {
// Get the index in selection by id
let index = selections.map(t=>t.id).indexOf(id)
if (index !== - 1) { // if the id have been found
selections[index][key] = value // It create the index "key" if not found, and replace the value if found
} else { // if the id have not been found
let tmp = {
id: id
}
tmp[key] = value
selections.push(tmp)
}
}
console.log(selections)
changeAttr(6, "color", "red")
console.log(selections)
changeAttr(3, "sex", "female")
console.log(selections)
changeAttr(6, "sex", "male")
console.log(selections)
changeAttr(6, "color", "yellow")
console.log(selections)
您可以运行代码片段来查看,我认为这就是您要寻找的
推荐阅读
- angular - 表单提交取消,因为表单未连接 Angular
- linux - 用于杀死不返回终端的 linux 进程的 Bash 脚本
- java - build.gradle 依赖项:fileTree vs. 项目 vs. 纯字符串
- python - 正则表达式:字符串中的单词索引
- unit-testing - 如何在 vscode 扩展单元测试中获取 extensionContext?
- apache - Blazor / Kestrel / Apache:如何正确配置?
- java - 堆栈中的 JavaFx 窗格不响应 MouseTransparent 或 PickOnBounds
- google-apps-script - 在特定时间在 Google Script 上触发警报
- c++ - CPtrList - 如何获取元素的索引?
- sql - 转换日期时间的意外结果