从另一个对象阵列重建对象阵列



目前,我在Javascript中有一个名为locations的数组,如下所述:

let locations = [
{
"id": "1",
"city": "Kermit",
"state": "TX",
},
{
"id": "2",
"city": "Bloomington",
"state": "MN",
},
{
"id": "3",
"city": "Pauls Valley",
"state": "OK",
},
{
"id": "4",
"city": "Colville",
"state": "WA",
},
{
"id": "5",
"city": "Jacksboro",
"state": "TX",
},
{
"id": "6",
"city": "Shallowater",
"state": "TX"    
}
]

使用Javascript,我需要从这个数组中创建另一个数组,方法是过滤出与locations数组中的单个数组具有相同状态的城市。所需输出:

locations = [
TX:[{
"id": "1",
"city": "Kermit",
"state": "TX",
},
{
"id": "5",
"city": "Jacksboro",
"state": "TX",
},
{
"id": "6",
"city": "Shallowater",
"state": "TX"    
}
],
MN:[
{
"id": "2",
"city": "Bloomington",
"state": "MN",
},
],
OK:[
{
"id": "3",
"city": "Pauls Valley",
"state": "OK",
},
],
WA:[
{
"id": "4",
"city": "Colville",
"state": "WA",
},
]
]

另外,我需要这个数组按字母顺序排序。如果有人能给我一个解决这种情况的好方法,那将是一个很大的帮助。

const locations = [
{ "id": "1", "city": "Kermit",       "state": "TX" },
{ "id": "2", "city": "Bloomington",  "state": "MN" },
{ "id": "3", "city": "Pauls Valley", "state": "OK" },
{ "id": "4", "city": "Colville",     "state": "WA" },
{ "id": "5", "city": "Jacksboro",    "state": "TX" },
{ "id": "6", "city": "Shallowater",  "state": "TX" }
];
const byState = {};
[...locations].sort((a,b) =>
a.state.localeCompare(b.state) || a.city.localeCompare(b.city)
).forEach(i => (byState[i.state]??=[]).push(i));
console.log(byState);

您可以按状态将位置分组。一旦实现了这一点,就可以将对象键值对转换为条目,对它们进行排序,然后将它们转换回对象。

const locations = [
{ "id": "1", "city": "Kermit",       "state": "TX" },
{ "id": "2", "city": "Bloomington",  "state": "MN" },
{ "id": "3", "city": "Pauls Valley", "state": "OK" },
{ "id": "4", "city": "Colville",     "state": "WA" },
{ "id": "5", "city": "Jacksboro",    "state": "TX" },
{ "id": "6", "city": "Shallowater",  "state": "TX" }
];
const sortObjectKeys = (obj) =>
Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
const groupedByState = sortObjectKeys(
locations.reduce((acc, location) => ({
...acc,
[location.state]: [...(acc[location.state] ?? []), {
...location
}]
}), {}));
console.log(groupedByState);
.as-console-wrapper { top: 0; max-height: 100% !important; }

如果你想放弃排序,只需减少数据:

const locations = [
{ "id": "1", "city": "Kermit",       "state": "TX" },
{ "id": "2", "city": "Bloomington",  "state": "MN" },
{ "id": "3", "city": "Pauls Valley", "state": "OK" },
{ "id": "4", "city": "Colville",     "state": "WA" },
{ "id": "5", "city": "Jacksboro",    "state": "TX" },
{ "id": "6", "city": "Shallowater",  "state": "TX" }
];
const groupedByState = 
locations.reduce((acc, { state, ...location }) => ({
...acc,
[state]: [...(acc[state] ?? []), { ...location, state }]
}), {});
console.log(groupedByState);
.as-console-wrapper { top: 0; max-height: 100% !important; }

最新更新