You can do something like this (I left capital
as an array, but it would be simpler if it were not):
const arr1 = [
{
name: {
common: 'Afghanistan',
official: 'Islamic Republic of Afghanistan',
},
capital: ['Kabul'],
},
{
name: {
common: 'Albania',
official: 'Republic of Albania',
},
capital: ['Tirana'],
},
];
const arr2 = [
{ capital: ['Tirana'], population: 2845955 },
{ capital: ['Kabul'], population: 2837743 },
];
const populationByCapital = new Map();
for (let el of arr2) {
populationByCapital.set(el.capital[0], el.population);
}
const arr3 = arr1.map((el) => {
return { ...el, population: populationByCapital.get(el.capital[0]) };
});
console.log(arr3);
this should give you:
[
{
name: {
common: 'Afghanistan',
official: 'Islamic Republic of Afghanistan'
},
capital: [ 'Kabul' ],
population: 2837743
},
{
name: { common: 'Albania', official: 'Republic of Albania' },
capital: [ 'Tirana' ],
population: 2845955
}
]
Note that it might break if there are two countries with the same capital names.
Edit
I see now that you were using the API from restcountries.com, thus changing capital
to a scalar is beyound your control. And there's a reason why it's an array -- South Africa has 3 capitals. The code should still work because it's the same API, and all 3 are listed in the same order in both endpoints.
But there are couple of complications. The country of Bouvet Island has apparently no capital, and so the array will be empty, and the country of Norfolk Island, and Jamaica have both "Kingston" as the capital. To address both of these issues you can change the key to include the name of the country together with the capital:
const populationByCapital = new Map();
for (let el of arr2) {
populationByCapital.set(el.capital[0] + el.name.common, el.population);
}
const arr3 = arr1.map((el) => {
return {
...el,
population: populationByCapital.get(el.capital[0] + el.name.common),
};
});