如何合并具有相似对象的2个数组? [英] How to merge 2 arrays with similar objects?

查看:36
本文介绍了如何合并具有相似对象的2个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IE:我有2个带有价格的数组,一个带有名称。

IE: I have 2 arrays one with prices, one with names.

一个带有价格的数组更长,我只希望最终数组的大小

The one with prices is longer, and I only want the final array to be the size of the smaller array with only names.

价格数组中的对象:

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

名称数组中的对象:

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

最终数组仅应包含 name 数组中存在的对象,但还具有价格数组中的价格键。

The final array should only contain objects that exist in the name array, but also have the price key from the prices array.

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

我已经使用NPM软件包完成了此任务,但是该软件包较旧,编译时存在错误:
运行NPM运行构建时出错(来自UglifyJs的index_bundle.js中的错误)

I had accomplished this using an NPM package, however the package is old and there is a bug when compiling: Error while running NPM run build (ERROR in index_bundle.js from UglifyJs)

我也在这里找到了这个答案:如何将2个数组与一个对象合并在一起?但是,没有任何答案有效。

I also found this answer here: How to merge 2 arrays with objects in one? However none of the answers worked. Neither was the array filtered by the smaller array, but the keys were not combined either.

推荐答案

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

An alternative is using the function map to generate a new array with the desired output.

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

This approach uses the function find to retrieve the specific object price related to an object name 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; }

这篇关于如何合并具有相似对象的2个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆