I am trying to achieve the following results in few lines of code.
Expected Result:
[{
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"
}, ....]
This is what I tried but again there is a property country
missing in the results. Expecting the shortest & efficient way to achieve this. Thank you for your responses.
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)
CodePudding user response:
The problem with Behram's and Ori's above is that the generated index is not correct; it will generate 1,2,3,1,2,3:
Instead remove the index value from the mappers:
let index = 1;
const results = obj.flatMap(({ country, cities }) => cities.map((city) => ({ active: true, id: index , name: city, country })));
console.log(result)
CodePudding user response:
You'll need another .map
to tie each city with its country first.
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)
You might consider the imperative version too. While less functional, it's a bit easier to understand.
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)
CodePudding user response:
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))
if you want a one-liner you can store that id in a parent anonymous function, ( but I will not suggest this as this is less readable )
console.log(((id) => obj.flatMap(({country, cities}) => cities.map(city => ({active:true, name: city, country,id: id}))))(0))
CodePudding user response:
follow this way:
const results = obj.flatMap(({ country, cities }) => {
return cities.map((city, index) => ({
active: true,
id: index 1,
name: city,
country: country
}));
});
console.log(results);