作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个对象数组,我想根据 javascript 中的公共(public)日期属性减少对象的数量
示例输入:
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
method 来实现这一点,因为预期的输出是输入数组的聚合。应用此方法的一种方法可能是;
result
)是否有任何日期与当前 item
匹配的项目>/li>结果
数组以下代码显示了此描述 - 希望对您有所帮助!
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);
关于javascript - 如何在javascript中组合具有相同键的数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138769/
我是一名优秀的程序员,十分优秀!