Skip to content
Advertisement

How to zip two arrays object in Javascript [closed]

I have two arrays object:

const arr1 = [{a: 'QQQ'}, {b: 'WWW'}]
const arr2 = [{a: 'EEE', b: 'RRR'}, {a: 'TTT', b: 'YYY'}]

Then I want the resulting array to be like this:

const results = [{'QQQ': 'EEE', 'WWW': 'RRR'}, {'QQQ': 'TTT', 'WWW': 'YYY'}]

Any way to do this? Thank you very much!

Advertisement

Answer

Not sure if this is the most efficient way to do this, but it works for the example provided. This method relies on some relatively newer features of JavaScript, but ES6 is widely supported, so it hopefully won’t be an issue in your case.

First, isolate the values in arr1 to be used as the object properties for the final result.

Then, re-map the objects of the second array by extracting the values from each object using Object.values() and reduce that to an object with the property names from the first array.

var arr1 = [{a: 'QQQ'}, {b: 'WWW'}];
var arr2 = [{a: 'EEE', b: 'RRR'}, {a: 'TTT', b: 'YYY'}];

var keys = arr1.reduce((valueArray,obj) => [...valueArray, ...Object.values(obj)],[]);

var results = arr2.map(o => Object.values(o).reduce((newObj,v,i) => ({...newObj,[keys[i]]:v}),{}),[])

console.log(results);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement