Consider utilizing the flatMap
method as shown below.
this.cities = this.states.flatMap(s => s.cities);
Take a look at the example below.
const states = [{
id: 1,
name: "New York",
cities: ['A', 'B']
}, {
id: 2,
name: "California",
cities: ['C', 'D']
}];
let cities = states.flatMap(s => s.cities);
console.log(cities);
Alternatively, you can also use the approach mentioned in your question. The issue was that your cities
object was being overwritten by each states.cities
. To prevent this, modify your code as follows to include both current and new values of cities
.
this.cities = [...this.cities, ...state.cities];
Note: Re-assigning the value as above will not work with const
. Make sure to declare cities
with let
. Alternatively, you can use .push
like
this.cities.push(...state.cities);
, which works with both
const
and
let
.
const states = [{
id: 1,
name: "New York",
cities: ['A', 'B']
}, {
id: 2,
name: "California",
cities: ['C', 'D']
}];
let cities = []
states.forEach((state, index, array) => {
// Uncomment the following line if declaring cities as const causes issues
//cities = [...cities, ...state.cities];
// Use .push if working with const variables
cities.push(...state.cities);
});
console.log(cities);