我如何在JavaScript中返回两个对象 [英] How can i return two objects in javascript
问题描述
例如
我有两个数组
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 }
];
我需要将这些数组合并为一个,以便如果日期匹配,则计数值将添加到该对象,如果计数不匹配,则会将两个对象都添加到该数组.
I need to merge these arrays into one so that if the day matches the count value adds to that object if it doesn't match it adds both objects to the array.
不知道解释不是很清楚,但是
Don't know if the explanation isn't so clear but
预期结果应该是这样的:
The expected result should be like this:
const data = [
{ day: "Mon", temp: 33.6, count: 2 },
{ day: "Tue", temp: 34.6 },
{ day: "Wed", temp: 33.1, count: 1 },
{ day: "Thur", count: 1 },
{ day: "Fri", temp: 35.6, count: 3 },
{ day: "Sat", count: 1 }
];
我试图像这样使用地图函数,但是不明白如果两个对象都不匹配,我该如何返回两个对象:
I am trying to use map function like so but can't understand how do I return both the objects if they don't match:
const data = tempData.map(temp => {
coughData.map(cough => {
if (temp.day === cough.day) {
return (temp.count = cough.count);
} else {
return cough;
}
});
return temp;
});
推荐答案
您可以首先合并数组的对象,然后使用地图来累积值.可以通过 day
属性来设置地图的键,这将使您可以将相关的对象属性分组在一起.然后,您可以使用 Array.from()
将您的Map转换回对象数组,如下所示:
You can first merge the objects of the arrays, and then use .reduce()
along with a Map to accumulate the values. The Map can be keyed by the day
property, which will allow you to group related object properties together. You can then use Array.from()
to transform your Map back into an array of objects like so:
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);
这篇关于我如何在JavaScript中返回两个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!