Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge two arrays (keys and values) into an object [duplicate]

Is there a common Javascript/Coffeescript-specific idiom I can use to accomplish this? Mainly out of curiosity.

I have two arrays, one consisting of the desired keys and the other one consisting of the desired values, and I want to merge this in to an object.

keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']
like image 478
Jorge Israel Peña Avatar asked Aug 03 '11 05:08

Jorge Israel Peña


People also ask

How do I merge two arrays together?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do I merge two arrays of objects in typescript without duplicates?

concat() can be used to merge multiple arrays together. But, it does not remove duplicates. filter() is used to identify if an item is present in the “merged_array” or not. Just like the traditional for loop, filter uses the indexOf() method to judge the occurrence of an item in the merged_array.

How do you merge an array of objects into a single object?

assign() method to convert an array of objects to a single object. This merges each object into a single resultant object. The Object. assign() method also merges the properties of one or more objects into a single object.


1 Answers

var r = {},
    i,
    keys = ['one', 'two', 'three'],
    values = ['a', 'b', 'c'];

for (let i = 0; i < keys.length; i++) {
    r[keys[i]] = values[i];
}

console.log(r);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 199
bjornd Avatar answered Sep 21 '22 18:09

bjornd