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);
To combine two arrays into an array of objects, use map() from JavaScript.
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.
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.
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]
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With