我想将初始数据转换为所需的结果,我正在努力将城市推送到数组并确保名称键是唯一的。
初始数据
[
{ "city": "Abbeville", "state": "Louisiana" },
{ "city": "Aberdeen", "state": "Maryland" },
{ "city": "Aberdeen", "state": "Mississippi" },
{ "city": "Aberdeen", "state": "South Dakota" },
{ "city": "Aberdeen", "state": "Washington" },
{ "city": "Abilene", "state": "Texas" },
{ "city": "Abilene", "state": "Kansas" },
{ "city": "Abingdon", "state": "Virginia" },
{ "city": "Abington", "state": "Massachusetts" },
{ "city": "Abington", "state": "Massachusetts" },
]
代码
let newCityStateObject = cities.map((item, index) => {
console.log("item ", item);
if (item) {
let object = {};
let citiesArray = [];
//set state and create empty array
if (object[item.state] === undefined) {
object.name = item.state;
object.cities = [].push(item.city);
} else {
//key exists so just push to array
if (object[item.state]) {
object.cities.push(item.city);
}
}
console.log("end ", object);
return object;
}
});
我现在的结果
[
{ state: 'Louisiana', cities: [] },
{ state: 'Maryland', cities: [] },
{ state: 'Mississippi', cities: [] },
{ state: 'South Dakota', cities: [] },
{ state: 'Washington', cities: [] },
{ state: 'Texas', cities: [] },
{ state: 'Kansas', cities: [] },
{ state: 'Virginia', cities: [] },
]
期望的结果
[
{
"name": "Kentucky",
"cities": [
"Louisville/Jefferson County",
"Lexington-Fayette",
"Bowling Green",
"Owensboro",
"Covington"
]
},
{
"name": "Maryland",
"cities": [
"Baltimore",
"Frederick",
"Rockville",
"Gaithersburg",
"Bowie",
"Hagerstown",
"Annapolis"
]
}
]
任何帮助/提示或指出解决此问题的正确方向将不胜感激。
翻阅古今
POPMUISE
相关分类