0

I want to merge the objects that are in the same index on two different arrays of objects. Which is the most simple and easy-to-understand way to go about this?

Here is the first array

const countries = [
    {
        "name": "Sweden",
        "nativeName": "Sverige"
    },
    {
        "name": "Norway",
        "nativeName": "Norge"
    },
    {
        "name": "Iceland",
        "nativeName": "Ísland"
    }
]

Here is the second array

const countryCodes = [
    {
        "country_id": "SE",
    },
    {
        "country_id": "NO",
    },
    {
        "country_id": "IS",
    }
]

I want to end up with this.


const countriesAndCodes = [
    {
        "name": "Sweden",
        "country_id": "SE",
        "nativeName": "Sverige"
    },
    {
        "name": "Norway",
        "country_id": "NO",
        "nativeName": "Norge"
    },
    {
        "name": "Iceland",
        "country_id": "IS",
        "nativeName": "Ísland"
    }
]
bitcasual
  • 83
  • 1
  • 7

1 Answers1

1

One option:

countries
  .map((country, i) => {
    const countryCode = countryCodes[i];
    const mergedCountry = ...; // Whatever technique to merge the two objects
    return mergedCountry;
  })

Though, I would probably look to use a zip function on a library like Lodash

Gaël J
  • 11,274
  • 4
  • 17
  • 32