Javascript 如何基于相同的值合并对象数组?
我有一组对象:Javascript 如何基于相同的值合并对象数组?,javascript,arrays,Javascript,Arrays,我有一组对象: var array = [{ country: "Austria", name: "2019-01-04T23:00:00.000Z", value: "1" }, { country: "Austria", name: "2019-01-11T23:00:00.000Z", value: "3" }, { country: "Austria", name: "2019-01-18T23:00:00.
var array = [{
country: "Austria",
name: "2019-01-04T23:00:00.000Z",
value: "1"
},
{
country: "Austria",
name: "2019-01-11T23:00:00.000Z",
value: "3"
},
{
country: "Austria",
name: "2019-01-18T23:00:00.000Z",
value: "1"
}
]
我希望通过操纵此操作来实现此结果:
var array = [{
country: "Austria",
series: [{
name: "2019-01-04T23:00:00.000Z",
value: "1"
},
{
name: "2019-01-11T23:00:00.000Z",
value: "3"
},
{
name: "2019-01-18T23:00:00.000Z",
value: "1"
}
]
}]
我读了很多问题,但没有一个对我有帮助。你可以做如下事情:
const result = array
.map(
c => ({
country: c.country,
series: array
.filter(d => d.country === c.country)
.map(
d => ({
name: d.name,
value: d.value
})
)
})
)
这应该做到:
var map = {};
for(var entity of array) {
if(!map[entity.country]) {
map[entity.country] = {
country: entity.country,
series: [
{
name: entity.name,
value: entity.value
}
]
};
}
else {
map[entity.country].series.push({
name: entity.name,
value: entity.value
});
}
}
var mappedArray = Object.values(map);
以下是没有for循环和可变变量的函数解决方案:
const result = array.reduce((carry, item) => {
if (!carry.includes(item.country)) {
carry.push(item.country);
}
return carry;
}, []).map(country => {
return {
country: country,
series: array.filter(item => item.country === country).map(item => {
return {
name: item.name,
value: item.value
};
})
};
你可以在数组中循环。用于分别获取属性的
country
和rest
。将每个唯一的国家/地区
添加到组
对象作为键,并将rest
对象推送到系列
数组中。然后使用以数组形式获取值
const数组=[{国家:“奥地利”,名称:“2019-01-04T23:00:00.000Z”,值:“1”},{国家:“奥地利”,名称:“2019-01-11T23:00:00.000Z”,值:“3”},{国家:“奥地利”,名称:“2019-01-18T23:00:00.000Z”,值:“1”};
常量组={};
array.forEach(({country,…rest})=>{
组[国家]=组[国家]|{国家,系列:[]};
组[国家]。系列。推送(rest)
})
console.log(Object.values(group))
它可以工作。我决定对这个答案进行投票,因为我认为它是一个简洁的表格,易于理解:)