首页 > 解决方案 > 用多个键和值填充对象数组

问题描述

我在@change 上有一个接收这些值的方法。

 changeAttr(id, key, value) {
  const selections = [];
},

id可以是任何数字,key可以是:color、size、sex 等...,value可以是:red、8、female 等。在第一次接收中,值可以是例如:id = 3、用户选择另一个选项。例如: , ,或 , , ...等key = "color"value = "red"id = 3key = "sex"value = "female"id = 5key = "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 添加它。

我希望我已经解释清楚了。非常感谢您的宝贵时间

标签: javascriptvue.js

解决方案


您可以简单地使用数组语法:

考虑到

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)

您可以运行代码片段来查看,我认为这就是您要寻找的


推荐阅读