Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two arrays into one javascript object

I have an array of data. In a there are 10 fields and in b there are 10 fields

var a = [ "siddharth", "sid", "anything", "something", "nothing", ]
var b = [ "23", "67", "10", "10", "90" ]

I am trying to create a JSON from these arrays as a as the key and b as values, as shown below:

{  "siddharth" : "23",  "sid" : "67" }

How can I achieve this using javascript or jquery. My current code is

 var convert = '{'+datatest.columnHeaders[i].name +":"+datatest.rows[0][i]+'}';
         pair   = convert;/*JSON.stringify(convert);*/
         array.pairArray.push(pair);
like image 557
Siddharth Avatar asked May 08 '15 13:05

Siddharth


People also ask

How do I combine two arrays of objects?

To combine two arrays into an array of objects, use map() from JavaScript.

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.

How do you combine arrays?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.


2 Answers

Assuming both arrays are always the same length:

var obj = {}
for (var i = 0; i < a.length; i++) {
    //or check with: if (b.length > i) { assignment }
    obj[a[i]] = b[i]
}
like image 74
tymeJV Avatar answered Sep 24 '22 17:09

tymeJV


var a = [ "siddharth", "sid", "anything", "something", "nothing" ];
var b = [ "23", "67", "10", "10", "90" ];

var c = {};
$.each( a, function(i,v) {
  c[ v ] = b[ i ];
});

$('body').append( JSON.stringify(c) );
//Output: {"siddharth":"23","sid":"67","anything":"10","something":"10","nothing":"90"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
like image 42
PeterKA Avatar answered Sep 25 '22 17:09

PeterKA