【发布时间】:2023-01-15 14:47:09
【问题描述】:
我试图在几行代码中实现以下结果。
预期结果:
[{
active: true,
id: 1,
name: "California",
country: USA
}, {
active: true,
id: 2,
name: "New York",
country:"USA"
},...
{
active: true,
id: 4,
name: "Moscow",
country:"Russia"
}, ....]
这是我尝试过的,但结果中再次缺少一个属性country。期望以最短且有效的方式实现这一目标。谢谢你的回复。
const obj = [
{
country: "USA",
cities: ["California", "New York", "Austin"]
},
{
country: "Russia",
cities: ["Moscow", "kazan", "Samara"]
}
];
//here the map of country is not there, wondering how to achieve this.
//obj.map(y => y.country).flatMap(x => x.cities)
const aa = obj.flatMap(x => x.cities)
.map((str, index) => ({ name: str, id: index + 1, active:true}));
console.log(aa)
【问题讨论】:
标签: javascript typescript