从具有重复值的数组创建对象

时间:2019-01-13 06:18:35

标签: javascript arrays object

我有一个重复值的数组:

[ ['Deer Skin', 1], ['Bear Skin', 1], ['Deer Skin', 1], ['Cougar Skin', 2] ... ]

我想通过index[0]的字符串值对其进行比较,并删除重复项,同时将结果存储在新对象中。

结果值如下:

[ {name: 'Deer Skin', quantity: 4}, {name: 'Bear Skin', quantity: 5}, {name: 'Cougar Skin', quantity: 4} ... ]

我不确定如何从这里继续。现在,我有一个对象数组,其中删除了所有初始重复数组值:


[
{name: "Deer Skin", quantity: 0}
{name: "Bear Skin", quantity: 0}
{name: "Cougar Skin", quantity: 0}
...

但是我不理解如何映射以下值:

[ ['Deer Skin', 1], ['Bear Skin', 1], ['Deer Skin', 1], ['Cougar Skin', 2] ... ]

到上面的对象。

3 个答案:

答案 0 :(得分:2)

您可以使用.reduce来实现。在这里,我已将累加器(acc)初始化为空对象{}。随着数组的迭代,三元运算符决定是否将数量添加到键(elem[0])的当前值中(我们仅在以前见过的情况下添加-如果我们试图添加到我们以前没有的内容上,我们将获得NaN作为我们的值)或是否要创建新的键值对(如果之前没有看到键值)。

请参见下面的工作示例:

const arr = [
  ['Deer Skin', 1],
  ['Bear Skin', 1],
  ['Deer Skin', 1],
  ['Cougar Skin', 2]
];

const res = arr.reduce((acc, elem) => {
  elem[0] in acc ? acc[elem[0]] += elem[1] : acc[elem[0]] = elem[1];
  return acc;
}, {});

console.log(res);

答案 1 :(得分:1)

使用Object.entries,array.reduce和数组解构:

const data = [
  ['Deer Skin', 1],
  ['Bear Skin', 1],
  ['Deer Skin', 1],
  ['Cougar Skin', 2]
];

const reduceData = (data) => data.reduce((acc, [key, count]) => {
  if (!acc[key]) acc[key] = 0; // If key doesn't exist yet, add and set count to zero
  acc[key] += count;
  return acc;
}, {});

console.log(reduceData(data));

// But if you want an array, use Object.entries
console.log(Object.entries(reduceData(data)));

答案 2 :(得分:0)

由于您没有提到要在其中存储唯一性的新对象的结构,因此可以执行以下操作:

const arrayItems = [ ['Deer Skin', 1], ['Bear Skin', 1], ['Deer Skin', 2], ['Cougar Skin', 2] ... ];
const deduplicatedObj = {};

for(let item of arrayItems){
    deduplicatedObj[item[0]] = item[1];
}

console.log(deduplicatedObj); // This should be an object with key as 'Deer Skin' and value as 1, and so on. 

由于您将值存储在对象中,并且对象只能具有唯一键,所以当您将item[1]分配给deduplicatedObj[item[0]]时,它将覆盖先前存在的值(如果有)。

deduplicatedObj看起来像这样:

deduplicatedObj = {
    'Deer Skin': 2,
    'Bear Skin': 1,
    'Cougar Skin': 2
}