【问题标题】:Merge two objects in different arrays [duplicate]合并不同数组中的两个对象[重复]
【发布时间】:2021-09-05 11:16:15
【问题描述】:

我想合并两个不同对象数组上相同索引中的对象。 哪种方法最简单易懂?

这是第一个数组

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

这是第二个数组

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

我想结束这个。


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

【问题讨论】:

  • 了解Array.map()
  • 阅读Object.assign(),然后尝试a.map( (e,i) => Object.assign(e,b[i]) )

标签: javascript


【解决方案1】:

一个选项:

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

不过,我可能希望在像 Lodash 这样的库上使用 zip 函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-20
    • 2021-07-28
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多