Skip to content Skip to sidebar Skip to footer

How To Merge 2 Arrays With Similar Objects?

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. Objects in

Solution 1:

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

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; }

Post a Comment for "How To Merge 2 Arrays With Similar Objects?"