5 回答
TA贡献1789条经验 获得超8个赞
day您可以收集对象中按分组的所有数据,并获取值作为结果集。
const
addToCollection = (collection, key) => o => Object.assign(collection[o[key]] ??= {}, o),
tempData = [{ day: "Mon", temp: 33.6 }, { day: "Tue", temp: 34.6 }, { day: "Wed", temp: 33.1 }, { day: "Fri", temp: 35.6 }],
coughData = [{ day: "Mon", count: 2 }, { day: "Wed", count: 1 }, { day: "Thur", count: 1 }, { day: "Fri", count: 3 }, { day: "Sat", count: 1 }],
collection = {};
tempData.forEach(addToCollection(collection, 'day'));
coughData.forEach(addToCollection(collection, 'day'));
console.log(Object.values(collection));
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1877条经验 获得超1个赞
您可以先合并数组的对象,然后.reduce()
与Map一起使用来累积值。地图可以通过day
属性作为键,这将允许您将相关的对象属性分组在一起。然后,您可以将Array.from()
Map 转换回对象数组,如下所示:
const tempData = [{ day: "Mon", temp: 33.6 }, { day: "Tue", temp: 34.6 }, { day: "Wed", temp: 33.1 }, { day: "Fri", temp: 35.6 }];
const coughData = [{ day: "Mon", count: 2 }, { day: "Wed", count: 1 }, { day: "Thur", count: 1 }, { day: "Fri", count: 3 }, { day: "Sat", count: 1 }];
const arr = [...tempData, ...coughData];
const result = Array.from(arr.reduce((map, {day, ...rest}) => {
const seen = map.get(day) || {day};
return map.set(day, {...seen, ...rest});
}, new Map).values());
console.log(result);
TA贡献1780条经验 获得超1个赞
const tempData = [
{ day: "Mon", temp: 33.6 },
{ day: "Tue", temp: 34.6 },
{ day: "Wed", temp: 33.1 },
{ day: "Fri", temp: 35.6 }
];
const coughData = [
{ day: "Mon", count: 2 },
{ day: "Wed", count: 1 },
{ day: "Thur", count: 1 },
{ day: "Fri", count: 3 },
{ day: "Sat", count: 1 }
];
const tempRes = [...tempData, ...coughData];
const result = tempRes.reduce((acc, curr) => {
const { day, ...rest } = curr;
acc[day] = acc[day] ? Object.assign({}, acc[day], rest) : curr
return acc;
}, {})
console.log(Object.values(result))
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1852条经验 获得超7个赞
let newArray = Array();
let longer = (tempData.length <= coughData.length) ? coughData.length :
tempData.length;
for(let i = 0, j = 0; i < longer; ++i, ++j) {
newArray.push(Object.assign(coughData[i], tempData[j]));
}
打印到控制台:
[ { day: 'Mon', count: 2, temp: 33.6 },
{ day: 'Tue', count: 1, temp: 34.6 },
{ day: 'Wed', count: 1, temp: 33.1 },
{ day: 'Fri', count: 3, temp: 35.6 },
{ day: 'Sat', count: 1 } ]
TA贡献1820条经验 获得超9个赞
您可以使用 Object.assign() javascript 函数。Object.assign()方法用于将一个或多个源对象的所有可枚举属性的值复制到一个目标对象。该方法将返回目标对象
就像这样:
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }
console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
添加回答
举报