代码之家  ›  专栏  ›  技术社区  ›  Leon Gaban

如何合并具有相似对象的两个数组[[关闭]

  •  -1
  • Leon Gaban  · 技术社区  · 6 年前

    带prices的数组较长,我只希望最后一个数组的大小与只带名称的较小数组的大小相同。

    {
      currency: 'BTC',
      price: '6500'
    },
    {
      currency: 'NEM',
      price: '1'
    },
    

    {
      currency: 'BTC',
      name: 'Bitcoin'
    }
    

    最后一个数组应该只包含 name price 钥匙从 prices

    {
      currency: 'BTC',
      name: 'Bitcoin',
      price: '6500'
    }
    

    我使用一个NPM包完成了这项工作,但是包很旧,编译时有一个bug: Error while running NPM run build (ERROR in index_bundle.js from UglifyJs)

    我在这里也找到了答案: How to merge 2 arrays with objects in one?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Ele    6 年前

    另一种方法是使用函数 map 生成具有所需输出的新数组。

    此方法使用函数 find 检索与对象名称相关的特定对象价格 name.currency === price.currency .

    let prices = [{  currency: 'BTC',  price: '6500'},{  currency: 'BSS',  price: '850'},{  currency: 'USD',  price: '905'}],
        names = [{  currency: 'BTC',  name: 'Bitcoin'},{  currency: 'BSS',  name: 'Bolivar'}],
        result = names.map(n => Object.assign({}, n, prices.find(p => p.currency === n.currency)));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }