javascript将数组放在键上

jchrr9hc  于 2022-12-02  发布在  Java
关注(0)|答案(5)|浏览(180)

我有一个简单的数组:

const arr = [
  {
    "id": 2,
    "color": "red"
  },
  {
    "id": 1,
    "color": "blue"
  },
  {
    "id": 2,
    "color": "yellow"
  },
];

我想创建一个散列Map,在其中为该键添加新颜色。
例如,我想在id: 3上添加color: green
现在,您可以看到没有id: 3
现在我在这里期待:

{
    2: [{color: "red"}]
    1: [{color: "blue"}, {color: "yellow"}],
    3: [{color: "green"}]
}

现在如果我想在id: 2上添加color: brown
在这种情况下,我期待:

{
    2: [{color: "red"}, {color: "brown"}]
    1: [{color: "blue"}, {color: "yellow"}],
    3: [{color: "green"}]
}

我已经创建了一个Playground:

const arr = [
  {
    "id": 2,
    "color": "red"
  },
  {
    "id": 1,
    "color": "blue"
  },
  {
    "id": 2,
    "color": "yellow"
  },
];

function addItem(id: number, colors: any) {
    let newArr = {[id]: colors};
  arr.forEach(function (obj) {

    newArr[obj.id].push({id: obj.color});
  });
  return newArr;
}

console.log(addItem(3, [{color: "green"}]))
console.log(addItem(1, [{color: "brown"}]))

这里我也想避免重复

moiiocjp

moiiocjp1#

function test(id, color) {
                for (var i = 0; i < arr.length; i++) {
                  if (arr[i].id == id) {
                    arr[i].color.push(color)
                  }
                }
              }

基本上,它将遍历数组,如果它的id匹配,它将添加您的颜色。

dnph8jn4

dnph8jn42#

下面的代码可以帮助您解决这个问题

const hashMap = new Map([
  [1, [{ color: "red" }]],
  [2, [{ color: "blue" }]],
  [3, [{ color: "yellow" }]],
]);

function addItem(id, colors) {
  hashMap.set(
    id,
    hashMap.has(id) ? [...hashMap.get(id).concat(colors)] : colors
  );

  return hashMap;
}
console.log(hashMap);
console.log(addItem(3, [{ color: "green" }]));
console.log(addItem(4, [{ color: "pink" }]));
ktecyv1j

ktecyv1j3#

let arr = [{
    "id": 2,
    "color": "red"
  },
  {
    "id": 1,
    "color": "blue"
  },
  {
    "id": 2,
    "color": "yellow"
  },
];

const groupBy = (xs, key) => {
  return xs.reduce(function(rv, x) {
    const y = {...x};
    delete y[key];
    (rv[x[key]] = rv[x[key]] || []).push(y);
    return rv
  }, {})
}

const addItem = (id, colors) => {
  // const newArr = arr... etc if you don't want to modify the existing array
  arr = arr.concat(colors.map(c => {
    c.id = id;
    return c
  }))

  const grouped = groupBy(arr, 'id')
  return grouped
}

console.log(addItem(3, [{
  color: "green"
}]))
console.log(addItem(1, [{
  color: "brown"
}]))
u0sqgete

u0sqgete4#

您可能会发现a class在封装数据时非常有用。
1.在初始化时,传入对象数组,并将其转换为带有数组值的a Map。(注意:您可以在此处使用对象作为替代)。
1.创建一个方法,如果新颜色不存在,则将其添加到相应的贴图数组中(即测试重复项)。

const arr=[{id:2,color:"red"},{id:1,color:"blue"},{id:2,color:"yellow"}];

class ColorMap {
        
  // `reduce` over the array to create a `colors` Map.
  // If the id doesn't exist on the map as a key,
  // create it, and assign an empty array to it.
  // Then push in the color to the array if
  // it doesn't already exist
  constructor(arr) {
    this.colors = arr.reduce((acc, obj) => {
      const { id, color } = obj;
      if (!acc.has(id)) acc.set(id, []);
      if (!this.colorExists(id, color)) {
        acc.get(id).push({ color });
      }
      return acc;
    }, new Map());
  }
  
  // Simple check to see if the color already
  // exists in the target array
  colorExists(id, color) {
    return this.colors?.get(id)?.find(obj => {
      return obj.color === color;
    });
  }

  // Similar to the `reduce` function, if the id doesn't have
  // a key on the map create one, and initialise an empty array,
  // and if the color doesn't already exist add it
  addColor(id, color) {
    if (!this.colors.has(id)) this.colors.set(id, []);
    if (!this.colorExists(id, color)) {
      this.colors.get(id).push({ color });
    }
  }

  // Return the colors map as a readable object
  showColors() {
    return Object.fromEntries(this.colors);
  }

}

const colorMap = new ColorMap(arr);

colorMap.addColor(3, 'green');
colorMap.addColor(1, 'brown');
colorMap.addColor(1, 'brown');

console.log(colorMap.showColors());

其他文件

r55awzrz

r55awzrz5#

const arr = [{
    "id": 2,
    "color": "red"
  },
  {
    "id": 1,
    "color": "blue"
  },
  {
    "id": 2,
    "color": "yellow"
  },
];

const grouped = arr.reduce((groups, current) => {
  if (!(current.id in groups)) {
    groups[current.id] = []
  }
  groups[current.id].push({
    color: current.color
  })
  return groups
}, {})

addItem(3, {
  color: "green"
})

addItem(1, {
  color: "brown"
})

console.log(grouped)

function addItem(id, item) {
  if (!(id in grouped)) {
    grouped[id] = []
  }
  grouped[id].push(item)
}

相关问题