如何使用嵌套数组作为JavaScript中的特定键值来创建新数组

时间:2018-09-24 14:41:32

标签: javascript arrays

如果有这样的数组:

let array = [ 
             {hash: "11223344", value: "abc"},
             {hash: "11223344", value: "def"},
             {hash: "22113344", value: "jkl"},
             {hash: "22113344", value: "zyw"},
             {hash: "33221144", value: "omn"},
             {hash: "33221144", value: "xyz"}
];

,我想遍历该数组并创建一个新数组,其中每个hash仅列出一次,并且每个列出给定value的键值都添加到数组中在单个hash的对象中,如下所示:

let newarray = [ 
             {hash: "11223344", value: ["abc", "def"]},
             {hash: "22113344", value: ["jkl", "zyw"]},
             {hash: "33221144", value: ["omn", "xyz"]},
]; 

我怎么到那里?

我在想类似的东西

array.map((item, i, self) => {
    let newArray =[];
    if(item.hash === newArray.hash){
        newArray.value.concat(item.value)
    } else {
        newArray.concat({hash: item.hash, value: [item.value]})
}

但是如何首先在value键中实例化该数组? 我对Array.prototype.map()的使用是否正确?

编辑:我被要求解释该问题与How to group an array of objects by key

有何不同

与链接相比,不需要对结果进行分组,我也不想使用LoDash之类的库。通过value键创建数组所提供的清晰度也具有一定价值。

我认为这里的答案还指出了使用索引的必要性,并提供了几种有效的工具,其中一些在其他问题的答案中没有提供。 reduce()Set

之类的工具

6 个答案:

答案 0 :(得分:2)

使用set获取唯一的哈希列表,然后使用filtermap匹配唯一集合上的每个项目。

let array = [ 
  {hash: "11223344", value: "abc"},
  {hash: "11223344", value: "def"},
  {hash: "22113344", value: "jkl"},
  {hash: "22113344", value: "zyw"},
  {hash: "33221144", value: "omn"},
  {hash: "33221144", value: "xyz"}
];

let a = [...new Set(array.map(i => i.hash))]
  .map(hash => {
    return { hash, values: array.filter(v => v.hash == hash).map(v => v.value) }
  })

console.log(a)

答案 1 :(得分:1)

您可以使用reduce函数返回一个新数组。在reduce回调内部,请使用findIndex查找哈希匹配的对象的索引。如果此哈希匹配,则更新value数组,否则创建一个新对象,设置其键和值并推送

let array = [{
    hash: "11223344",
    value: "abc"
  },
  {
    hash: "11223344",
    value: "def"
  },
  {
    hash: "22113344",
    value: "jkl"
  },
  {
    hash: "22113344",
    value: "zyw"
  },
  {
    hash: "33221144",
    value: "omn"
  },
  {
    hash: "33221144",
    value: "xyz"
  }
];

let reducedArray = array.reduce(function(acc, curr) {
  let getHashIndex = acc.findIndex(function(item) {
    return item.hash === curr.hash;
  })
  if (getHashIndex === -1) {
    let obj = {};
    obj.hash = curr.hash;
    obj.value = [];
    obj.value.push(curr.value);
    acc.push(obj)
  } else {
    acc[getHashIndex].value.push(curr.value)

  }
  return acc;
}, [])

console.log(reducedArray)

答案 2 :(得分:0)

您可以使用Map,并使用Array.from渲染收集的项目。

var array = [{ hash: "11223344", value: "abc" }, { hash: "11223344", value: "def" }, { hash: "22113344", value: "jkl" }, { hash: "22113344", value: "zyw" }, { hash: "33221144", value: "omn" }, { hash: "33221144", value: "xyz" }],
    grouped = Array.from(
        array.reduce((map, { hash, value }) =>
            map.set(hash, (map.get(hash) || []).concat(value)), new Map),
        ([hash, value]) => ({ hash, value })
    );
    
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

您可以像下面一样使用reduce

let array = [ 
   {hash: "11223344", value: "abc"},
   {hash: "11223344", value: "def"},
   {hash: "22113344", value: "jkl"},
   {hash: "22113344", value: "zyw"},
   {hash: "33221144", value: "omn"},
   {hash: "33221144", value: "xyz"}
];

let result = array.reduce((acc, ele) => {
   let index = acc.findIndex(e => e.hash === ele.hash);
   if (index == -1) {
    acc.push({
      hash: ele.hash,
      value: [ele.value]
    })
   } else {
    acc[index].value.push(ele.value);
   }
   return acc;
}, []);

console.log(result);

答案 4 :(得分:0)

看看下面的代码,其中我们维护之前遇到的哈希索引,并将值插入现有对象,否则在结果数组中插入新对象。

let data = [{
    hash: "11223344",
    value: "abc"
  },
  {
    hash: "11223344",
    value: "def"
  },
  {
    hash: "22113344",
    value: "jkl"
  },
  {
    hash: "22113344",
    value: "zyw"
  },
  {
    hash: "33221144",
    value: "omn"
  },
  {
    hash: "33221144",
    value: "xyz"
  }
];


function aggregateValues(arr) {
  let hashMap = {};
  let result = [];
  arr.forEach((o) => {
    if (hashMap[o.hash] !== undefined) {
      result[hashMap[o.hash]].value.push(o.value);
    } else {
      hashMap[o.hash] = result.length;
      result.push({
        hash: o.hash,
        value: [o.value]
      });
    }
  })
  return result;
}

console.log(aggregateValues(data))

答案 5 :(得分:0)

您可以简单地使用for循环来实现此目的:

array = [ 
     {hash: "11223344", value: "abc"},
     {hash: "11223344", value: "def"},
     {hash: "22113344", value: "jkl"},
     {hash: "22113344", value: "zyw"},
     {hash: "33221144", value: "omn"},
     {hash: "33221144", value: "xyz"}
];

newArray = []
for (var i = array.length - 1; i >= 0; i--) {

    if (newArray[array[i].hash] == null) {
        newArray[array[i].hash] = [array[i].value];
    } else {
        newArray[array[i].hash].push(array[i].value)
    }
}
console.log(newArray);