Skip to content Skip to sidebar Skip to footer

Merge Two Array Into One Array With Key Value Relationship

Javascript: I have two arrays. one with key other one with value.. i need to merge them together in key value pairs into one array. arr2 = ['anik','manik','philip']; arr1 =[1,2,3]

Solution 1:

You can do it like this.
array3 will be the desired result.

array1 = ["anik", "manik", "philip"];
array2 = [1, 2, 3];
array3 = [];

array1.forEach(function(e, i) {
  array3.push(
    e + ":" + array2[i]
  );
})

document.write(JSON.stringify(array3));

This is the better way:

var array1 = ["anik", "manik", "philip"];
var array2 = [1, 2, 3];

var array3 = array1.map(function(e, i) {
  return e + ":" + array2[i];
})

document.write(JSON.stringify(array3));

Solution 2:

var keys = ["anik","manik","philip"];
var values = [1,2,3];
var results = keys.map(function(k, index){
  return {[k]:values[index]}
});
console.log(results);

fiddle


Post a Comment for "Merge Two Array Into One Array With Key Value Relationship"