JavaScript:将两个列表合并到JSON对象中,并在不使用ES6的情况下将相同的键值附加在一起

时间:2019-03-06 22:46:09

标签: javascript arrays

一个快速的JavaScript问题。给定两个数组,并假设它们的长度相同。我想将两个数组组合成一个json对象数组。另外,如果代码已存在于数组中,则将错误附加到现有的.error元素中。如果有人可以提供使用原始javascript而不是ES6的解决方案,将不胜感激。

var codes = ["12345", "12345","67890", "67890", "67890","67890","12092", "12092"];

var errors = ["12345 error 1","12345 error 2","67890 error 1","67890 error 2","67890 error 3","67890 error 4","12092 error 1","12092 error 2"];

应转换为

{
    "code": "12345",
    "error": "12345 error 1, 12345 error 2"
},
{
    "code": "67890",
    "error": "67890 error 1, 67890 error 2, 67890 error 3, 67890 error 4, 67890 error 5"
},
{
    "code": "12092",
    "error": "12092 error 1 , 12092 error 2"
}

1 个答案:

答案 0 :(得分:0)

您可以使用map组合它们,然后对其进行分组并将其转换为对象数组,然后

ValueError: setting an array element with a sequence as an error.

如果您真的希望错误是单个字符串,请添加.join()

const codes = ["12345", "12345","67890", "67890", "67890","67890","12092", "12092"];
const errors = ["12345 error 1","12345 error 2","67890 error 1","67890 error 2","67890 error 3","67890 error 4","12092 error 1", "12092 error 2"];

const res = Array.from(
    codes.map((e, i) => ({code: e, errors: errors[i]}))
        .reduce((a, b) => a.set(b.code, (a.get(b.code) || []).concat(b.errors)), new Map))
    .map(([k, v]) => ({code:k, errors: v}));
console.log(res);

ES6之前的版本

.map(([k, v]) => ({code:k, errors: v.join()}));