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);
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]
}
You can create plain object and use it as the mapping container:
var a = [ "siddharth", "sid", "anything", "something", "nothing" ];
var b = [ "23", "67", "10", "10", "90" ];
var obj = {};
for ( i = 0; i < a.length; i++) {
obj[a[i]] = b[i];
}
alert(JSON.stringify(obj));
Please refer to How to create a hash or dictionary object in JavaScript for more information
This example is equal to tymeJVs example, but uses forEach loop for array. For me it looks shorter.
var obj = {};
a.forEach(function(item, i) {
obj[item] = b[i];
});
console.log(JSON.stringify(obj)); // {"siddharth":"23","sid":"67","anything":"10","something":"10","nothing":"90"}
You would need quotation marks around the name and the value, otherwise you end up with a string like {siddharth:23,sid:67}
:
// mock the data
var datatest = {
columnHeaders: [ { name: "siddharth" }, { name: "sid" }, { name: "anything" }, { name: "something" }, { name: "nothing" } ],
rows: [[ "23", "67", "10", "10", "90" ]]
};
var json = '{';
for (var i = 0; i < datatest.columnHeaders.length; i++) {
if (i > 0) json += ',';
json += '"' + datatest.columnHeaders[i].name + '":"' + datatest.rows[0][i] +'"';
}
json += '}';
// show result in StackOverflow snippet
document.write(json);
Shortest i can get using ES6 fat arrow function, map, reduce & computed property names
var a = ["siddharth", "sid", "anything", "something", "nothing", ]
var b = ["23", "67", "10", "10", "90"]
const mergeArrToJSON = (a, b) => a
.map((item, i) => ({[item]: b[i]}))
.reduce((json,val)=>Object.assign({},json,val))
console.log(mergeArrToJSON(a, b))
If you are willing to add another famous third-party javascript utility library
Lodash, use zipObject:
_.zipObject(a, b);
Underscore, use object:
_.object(a, b);
If you are free to use additional plugin then
UNDERSCORE
is what you are looking for
_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}
Single line code.
Just include this js
https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js