14

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);
1
  • Duplicate question? Isn't JSON.stringify(convert); working? Commented May 8, 2015 at 13:25

8 Answers 8

16

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]
}
Sign up to request clarification or add additional context in comments.

Comments

3

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>

Comments

3

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"}

Comments

3

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))

Comments

2

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

Comments

1

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);

Comments

0

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.