一个快速的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"
}
答案 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()}));