简体   繁体   English

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

[英]How to reduce two depended arrays into an object in JavaScript?

I have two JavaScript arrays of strings as a result from a SQL query (each array is one column in a result) which may contain duplicities like: 我有两个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"]

and I need to reduce them into an object like: 我需要将它们缩减成如下对象:

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

So basically, for each key, value pair, the value should be a reduced list of unique values from an arrTwo. 所以基本上,对于每个键值对,值应该是arrTwo中唯一值的简化列表。

I have tried: 我试过了:

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

which gives me: 这给了我:

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

but I need arrTwo[i] part to be reduced list of values instead of last value for each key. 但我需要arrTwo [i]部分减少值列表而不是每个键的最后一个值。

This may have an elegant one-line solution but I am new in JavaScript and I can't find the proper solution (I think a loop is not necessary here). 这可能有一个优雅的单行解决方案,但我是JavaScript的新手,我找不到合适的解决方案(我认为这里不需要循环)。

You could take a Set and collect all values. 您可以采取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); 

Use reduce on one of the first array and use index to access property from second array 在第一个数组之一上使用reduce,并使用index从第二个数组访问属性

 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) 

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM