使用FlatMap/Map为每个对象添加父属性



我试图在几行代码中实现以下结果。

预期结果:

[{
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)

Behram's和Ori's上面的问题是生成的索引不正确;它将生成1,2,3,1,2,3:

从映射器中删除索引值:

let index = 1;
const results = obj.flatMap(({ country, cities }) => cities.map((city) => ({ active: true, id: index++, name: city, country })));
console.log(result)

你需要另一个.map将每个城市与其国家联系起来。

const obj = [
{
country: "USA",
cities: ["California", "New York", "Austin"]
},
{
country: "Russia",
cities: ["Moscow", "kazan", "Samara"]
}
];

const aa = obj
.flatMap(({ cities, country }) => cities.map(city => ({ name: city, country })))
.map((obj, index) => ({ ...obj, id: index + 1, active:true}));
console.log(aa)

您也可以考虑命令式版本。虽然功能较差,但更容易理解。

const obj = [
{
country: "USA",
cities: ["California", "New York", "Austin"]
},
{
country: "Russia",
cities: ["Moscow", "kazan", "Samara"]
}
];
const aa = [];
let id = 1;
for (const { cities, country } of obj) {
for (const name of cities) {
aa.push({ name, country, id: id++, active: true });
}
}
console.log(aa)

function transform(obj) {
let id = 0;
return obj.flatMap(({country, cities}) => cities.map(city => ({active:true, name: city, country,id: ++id})))
}

console.log(transform(obj))

如果您想要一个单行代码,您可以将该id存储在父匿名函数中,(但我不建议这样做,因为这样可读性较差)

console.log(((id) => obj.flatMap(({country, cities}) => cities.map(city => ({active:true, name: city, country,id: ++id}))))(0))

如下:

const results = obj.flatMap(({ country, cities }) => {
return cities.map((city, index) => ({
active: true,
id: index + 1,
name: city,
country: country
}));
});
console.log(results);

最新更新