我有一组数据。在a
中有10个字段,b
中有10个字段
var a = [ "siddharth", "sid", "anything", "something", "nothing", ]
var b = [ "23", "67", "10", "10", "90" ]
我正在尝试从这些数组创建JSON
作为密钥a
b
作为值,如下所示:
{ "siddharth" : "23", "sid" : "67" }
如何使用javascript
或jquery
实现此目的。我目前的代码是
var convert = '{'+datatest.columnHeaders[i].name +":"+datatest.rows[0][i]+'}';
pair = convert;/*JSON.stringify(convert);*/
array.pairArray.push(pair);
答案 0 :(得分:14)
假设两个数组的长度始终相同:
var obj = {}
for (var i = 0; i < a.length; i++) {
//or check with: if (b.length > i) { assignment }
obj[a[i]] = b[i]
}
答案 1 :(得分: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"}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
答案 2 :(得分:2)
此示例等于tymeJVs示例,但对数组使用forEach循环。对我来说,它看起来更短。
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"}
答案 3 :(得分:1)
您可以创建普通对象并将其用作映射容器:
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));
有关详细信息,请参阅How to create a hash or dictionary object in JavaScript
答案 4 :(得分:1)
您需要在名称和值周围加上引号,否则最终会得到{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);
答案 5 :(得分:1)
最短的我可以使用ES6胖箭头功能,map,reduce&amp; 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))
&#13;
答案 6 :(得分:0)
如果您愿意添加另一个着名的第三方JavaScript实用程序库
Lodash,使用zipObject:
_.zipObject(a, b);
下划线,使用object:
_.object(a, b);
答案 7 :(得分:0)
如果您可以自由使用其他插件,那么
是您正在寻找的
_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}
单行代码。 只需包含此js
https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js