如何在JavaScript中将两个相关的数组减少为一个对象?

3

我有两个JavaScript字符串数组,它们是从SQL查询结果中得到的(每个数组是一个列),它们可能包含重复的内容,例如:

arrOne = ["key_1", "key_1", "key_2", "key_3", "key_1", "key_1"]
arrTwo = ["val_1", "val_1", "val_3", "val_3", "val_2", "val_3"]

我需要将它们转换成类似下面的对象:

并且我需要将它们缩减为一个对象,例如:

newObj = {
  key_1: ["val_1", "val_2", "val_3"],
  key_2: ["val_3"],
  key_3: ["val_3"]
}

基本上,对于每个键值对,值应该是来自 arrTwo 的唯一值的缩减列表。

我尝试过:

let newObj = arrOne.reduce((o, k, i) => ({...o, [k]: arrTwo[i]}), {})

这给了我:

{ key_1: 'val_3', key_2: 'val_3', key_3: 'val_3' }

但我需要arrTwo [i]部分成为每个键的缩小值列表,而不是最后一个值。

这可能有一个优雅的一行解决方案,但我是JavaScript新手,我找不到正确的解决方案(我认为这里不需要循环)。

3个回答

3
你可以使用 Set 来收集所有的数值。

var arrOne = ["key_1", "key_1", "key_2", "key_3", "key_1", "key_1"],
    arrTwo = ["val_1", "val_1", "val_3", "val_3", "val_2", "val_3"],
    newObj = arrOne.reduce(
        (o, k, i) => ({ ...o, [k]: [...new Set([...(o[k] || []), arrTwo[i]])] }),
        {}
    );

console.log(newObj);


谢谢!这正是我正在寻找的 :) - Pirastrino

0

在第一个数组上使用reduce函数,并使用索引从第二个数组中访问属性

var arrOne = ["key_1", "key_1", "key_2", "key_3", "key_1", "key_1"]
var arrTwo = ["val_1", "val_1", "val_3", "val_3", "val_2", "val_3"]

let newObj = arrOne.reduce(function(acc, curr, index) {
  // check if the object has such key and if it dont contain the corresponding value 
  if (acc[curr] && acc[curr].indexOf(arrTwo[index]) === -1) {
    acc[curr].push(arrTwo[index])
  } else {
    acc[curr] = [];
    acc[curr].push(arrTwo[index])

  }

  return acc;
}, {});

console.log(newObj)


0

const arrOne = ["key_1", "key_1", "key_2", "key_3", "key_1", "key_1"];
const arrTwo = ["val_1", "val_1", "val_3", "val_3", "val_2", "val_3"];
console.log(
  arrTwo.reduce((a, c, i) => {
    if (a[arrOne[i]].indexOf(c) == -1) a[arrOne[i]].push(c);
    return a;
  }, arrOne.reduce((a, c) => {
    a[c] = []; return a;
  }, {})));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接