[英]Reduce an array of objects by multiple keys and push them into a subset array
我有以下 object:
const array = [
{city: 'Auckland', country: 'New Zealand', date: '2024-02-03T00:00:00'},
{city: 'Manchester', country: 'United Kingdom', date: '2024-02-04T00:00:00'},
{city: 'Manchester', country: 'United Kingdom', date: '2024-02-09T00:00:00'},
{city: 'Edinburgh', country: 'Scotland', date: '2024-02-05T00:00:00'},
{city: 'Manchester', country: 'United States', date: '2024-02-03T00:00:00'},
{city: 'Manchester', country: 'United States', date: '2024-02-09T00:00:00'}
]
我希望它像下面這樣分組:
{
city: 'Auckland',
items: [
{city: 'Auckland', country: 'New Zealand', date: '2024-02-03T00:00:00'}
]
},
{
city: 'Manchester',
items: [
{city: 'Manchester', country: 'United Kingdom', date: '2024-02-04T00:00:00'},
{city: 'Manchester', country: 'United Kingdom', date: '2024-02-09T00:00:00'}
]
},
{
city: 'Edinburgh',
items: [
{city: 'Edinburgh', country: 'Scotland', date: '2024-02-05T00:00:00'}
]
},
{
city: 'Manchester',
item: [
{city: 'Manchester', country: 'United States', date: '2024-02-03T00:00:00'},
{city: 'Manchester', country: 'United States', date: '2024-02-09T00:00:00'}
]
}
我嘗試了多種不同的方法。 我在 .net 上搜索了類似的線程,尤其是在此處,但沒有找到類似的線程。 我試過以下方法:
array.reduce((r, item) => {
r[item.city] = r[item.city] || []
r[item.city].push(item)
return r
}, Object.create(null))
但是,這顯然沒有考慮“國家”。 我也嘗試了以下但只返回所需組中的第一項:
const cities = {};
for (let p of array) {
const { city, country } = p;
const groupByCity = JSON.stringify([city]);
const groupByCountry = JSON.stringify([country]);
if (!(groupByCity in cities)) {
cities[groupByCity] = { city: city, items: []};
cities[groupByCity].items.push(p);
} else if (groupByCity in examCities && cities[groupByCity].country !== p.country) {
cities[`${groupByCity}2`] = { city: city, items: []};
cities[`${groupByCity}2`].items.push(p);
}
}
有很多方法可以做到這一點,這是我使用 reduce 和 map 的方法:
const array = [{ city: 'Auckland', country: 'New Zealand', date: '2024-02-03T00:00:00' }, { city: 'Manchester', country: 'United Kingdom', date: '2024-02-04T00:00:00' }, { city: 'Manchester', country: 'United Kingdom', date: '2024-02-09T00:00:00' }, { city: 'Edinburgh', country: 'Scotland', date: '2024-02-05T00:00:00' }, { city: 'Manchester', country: 'United States', date: '2024-02-03T00:00:00' }, { city: 'Manchester', country: 'United States', date: '2024-02-09T00:00:00' } ] const result = Object.entries(array.reduce((acc, curr) => { const key = `${curr.city}|${curr.country}` return {...acc, [key]: key in acc? [...acc[key], curr]: [curr] } }, {})).map(([key, value]) => ({ city: value[0].city, items: value })) console.log(result)
基本上,我按{city}|{country}
對它們進行分組,並使用reduce
形成一個 object ,然后使用map
將該 object 轉換為所需的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.