我有一个对象数组,我想根据JavaScript中的common date属性减少对象的数量
输入样例:
const data = [
{date:"1 Nov", foo: 123},
{date:"1 Nov", bar: 456},
{date:"2 Nov", foo: 234},
{date:"2 Nov", bar: 567}
];
预期产量
const data = [
{date:"1 Nov", foo: 123, bar: 456},
{date:"2 Nov", foo: 234, bar: 567},
];
看到预期的输出是输入数组的集合,也许您可以使用该Array#reduce
方法来实现此目的。一种应用此方法的方法可能是:
result
如下所示)是否有日期与当前数组匹配的任何项目item
result
数组中下面以代码显示此描述-希望对您有所帮助!
const data = [
{date:"1 Nov", foo: 123},
{date:"1 Nov", bar: 456},
{date:"2 Nov", foo: 234},
{date:"2 Nov", bar: 567}
];
const output = data.reduce((result, item) => {
const i = result.findIndex(resultItem => resultItem.date === item.date)
if(i === -1) {
// No item in current result array found that matches the date of item
// so add item to result array
result.push(item)
}
else {
// An item found with date matching item in current result so combine
// the two into a new object and assign this back into our result
// array
result[i] = { ...result[i], ...item }
}
return result
}, [])
console.log(output);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句