以下示例中的我的问题。我几乎在那里建立了一个新的对象数组并重命名了一些属性。但是那里只显示国家。其他属性是“未定义”。
我试图做这样的事情:name: t.cities[0].id,
但是此方法并未遍历以下对象,仅遍历第一个
预先感谢
let data = [
{
"country": "italy",
"cities": [
{
"id": "milan",
"count": "1366180",
},
{
"id": "rome",
"count": "2870500",
},
{
"id": "torino",
"count": "870952",
}
]
},
{
"country": "france",
"cities": [
{
"id": "paris",
"count": "2148327",
},
{
"id": "marseille",
"count": "869815",
},
{
"id": "lyon",
"count": "516092",
}
]
}
]
let rename = data.map( a => ({
country: a.country,
cities: data.map( t => ({
name: t.cities.id,
population: t.cities.count,
}))
}));
console.log( rename )
答案 0 :(得分:2)
内部data.map()
应该是a.cities.map()
。并且此地图接收单个城市对象,您可以直接访问id
和count
属性,它们不需要是嵌套属性。
let data = [
{
"country": "italy",
"cities": [
{
"id": "milan",
"count": "1366180",
},
{
"id": "rome",
"count": "2870500",
},
{
"id": "torino",
"count": "870952",
}
]
},
{
"country": "france",
"cities": [
{
"id": "paris",
"count": "2148327",
},
{
"id": "marseille",
"count": "869815",
},
{
"id": "lyon",
"count": "516092",
}
]
}
]
let rename = data.map( a => ({
country: a.country,
cities: a.cities.map( city => ({
name: city.id,
population: city.count,
}))
}));
console.log( rename )