3 回答

TA贡献1862条经验 获得超7个赞
您可以采用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);

TA贡献1770条经验 获得超3个赞
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;
}, {})));

TA贡献1868条经验 获得超4个赞
在第一个数组中的一个上使用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)
添加回答
举报