Reputation: 416
I have the following code.
I have this array of array data.
const data = [
[
{
city: "Phnom Penh",
country: "KH"
},
{
city: "Tirana",
country: "AL"
},
{
city: "Andorra la Vella",
country: "AD"
}
],
[
{
city: "Mariehamn",
country: "AX"
}
],
[]
];
I am trying to print all city
in the new variable and then want to show in select
const cities = data.map((el) => el).map((el, idx) => el[idx]?.city);
<select>
{cities.map((el) => (
<option value={el} key={idx}>
{el}
</option>)}
</select>
But I am getting only first city.
The output now is
(3) ["Phnom Penh", undefined, undefined]
But the output should be
(4) ["Phnom Penh", "Tirana", "Andorra la Vella", "Mariehamn"]
Please help me to correct my code.
Thanks.
Upvotes: 0
Views: 444
Reputation: 111
const cities = data.flat().map(item => item.city);
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
The Javascript map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally, the map() method is used to iterate over an array and calling function on every element of the array.
console.log(cities);
// Output: ["Phnom Penh", "Tirana", "Andorra la Vella", "Mariehamn"]
Upvotes: 1
Reputation: 148
Since flat may not be available on every environment I am providing with an alternative solution:
let cities = [];
data.forEach(el=> {
el.forEach(element => {
cities.push(element.city);
});
});
Upvotes: 0