如何在JavaScript中将两个依赖数组简化为一个对象?

我有两个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的新手,我找不到合适的解决方案(我认为这里不需要循环)。


慕的地10843
浏览 205回答 3
3回答

牧羊人nacy

您可以采用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);

德玛西亚99

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;  }, {})));

MYYA

在第一个数组中的一个上使用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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript