Merge two arrays into one javascript object

2020-02-28 03:59发布

问题:

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:

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


回答2:

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>



回答3:

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



回答4:

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


回答5:

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



回答6:

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



回答7:

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


回答8:

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