Use of Object.entries()



有没有一种方法可以通过使用Object.entries((来简化这段代码?我想删除新的Map((。

const err = [{ 
'id': 1, 
'error': ["Error 1", "Error2"]
}]
const warn = [{ 
'id': 1, 
'warning': ["Warn 1", "Warn 2"]
}]
const map = new Map();
err.forEach(item=> map.set(item.id, item));
warn.forEach(item=> map.set(item.id, {...map.get(item.id), ...item}));
const combined = Array.from(map.values());
console.log(combined)

尝试:

const map = new Map(Object.entries(err));
warn.forEach(item=> map.set(item.id, {...map.get(item.id), ...item}));
const combined = Array.from(map.values());
console.log(combined)

输出应该仍然是相同的

[{ 
'id': 1, 
'error': ["Error 1", "Error2"],
'warning': ["Warn 1", "Warn 2"] 
}]

您可以使用Array.prototype.map()new Map()参数创建键/值对。

const err = [{
'id': 1,
'error': ["Error 1", "Error 2"]
}]
const warn = [{
'id': 1,
'warning': ["Warn 1", "Warn 2"]
}]

const map = new Map(err.map(el => [el.id, el]));
warn.forEach(el => map.get(el.id).warning = el.warning);
const combined = Array.from(map.values());
console.log(combined)
Object.entries()没有用处,因为键是数组索引,而不是id属性。

如果您希望每个数组有1个以上的项目,您可以执行:

const err = [{ 
'id': 1, 
'error': ["Error 1", "Error2"]
}]
const warn = [{ 
'id': 1, 
'warning': ["Warn 1", "Warn 2"]
}]

const newObj = err.map( (item,i) => Object.assign({},item,warn[i]));
console.log(newObj)

如果最终对象依赖于其他数组,并且您事先知道它们的长度正好为1,那么更简单:

const err = [{ 
'id': 1, 
'error': ["Error 1", "Error2"]
}]
const warn = [{ 
'id': 1, 
'warning': ["Warn 1", "Warn 2"]
}]

const newArr = [Object.assign({},err[0],warn[0])]
console.log(newArr)

对象条目用于对象,而不是数组。但是,您可以使用reduce进行分组转化为对象,然后将他的值转化为数组。

const err = [{
'id': 1,
'error': ["Error 1", "Error 2"]
}]
const warn = [{
'id': 1,
'warning': ["Warn 1", "Warn 2"]
}]

var combined = Object.values(err.concat(warn).reduce(function(agg, item) {
agg[item.id] = { ...agg[item.id], ...item}
return agg;
}, {}));
console.log(combined)

最新更新