2 回答
TA贡献1780条经验 获得超5个赞
您基本上是按州对城市进行分组。首先,array.map这不是解决此问题的正确方法,因为当您分组时,输入项的编号可能与输出项的编号不匹配。array.reduce是更好的选择。
let newCityStateObject = cities.reduce((acc, item, index) => {
if (item) {
// this object has state as key, and the desired output array’s item as value
const object = acc.obj;
// if state not found, create new record
if (object[item.state] === undefined) {
const record = { name: item.state, cities: [] }
object[item.state] = record;
acc.array.push(record);
}
const record = object[item.state];
record.cities.push(item.city);
}
return acc;
}, { obj: {}, array: [] }).array;
TA贡献1765条经验 获得超5个赞
这是另一种考虑方法:
let newCityStateObject = () => {
const statesArr = Array.from(cities, (item) => item.state);
// Remove state duplications
const filteredStates = [...new Set(statesArr)];
// Initializing the name and cities object and array
let result = filteredStates.map((item) => {
return { name: item, cities: [] };
});
// For each cite item, fetch the city to its corresponding result by state
cities.forEach((item) =>
result
.find((element) => element.name === item.state)
.cities.push(item.city)
);
return result;
}
添加回答
举报