Skip to content
Advertisement

Merging Javascript arrays without concat

I have two arrays that I need to combine. Most of the advice on combining arrays I can find use concat. But I don’t want to add to the end of an array, I need to add a key/value pair from array1 to each object in array2.

I need to merge this array1:

JavaScript

With this array2:

JavaScript

In a new combined array, I need to add a key of title to each object with the value from the first array so that the resulting array looks like this:

JavaScript

Advertisement

Answer

You can do a simple for-loop in the second array inserting the new title property taken from the first one. But, if you want a function that gives you a new array without modifying the sources, then one solution is to make a new array mapping a clone of the objects in the second array with the strings in the first one, something like this:

JavaScript

Here you have an example using a function with your arrays:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement