将多个数组组合成一个对象,以第一个数组项为关键

时间:2014-09-30 20:48:34

标签: javascript arrays json

我有以下数组

var category = ['Guitar', 'Bass', 'Amps'];


var platform_a = ['platform-a1','platform-a2','platform-a3'];
var platform_b = ['platform-b1','platform-b2','platform-b3'];
var platform_c = ['platform-c1','platform-c2','platform-c3'];

我想把它们转换成一个看起来像这样的json

{
    "Guitar":["platform-a1","platform-a2","platform-a3"],
    "Bass":["platform-b1","platform-b2","platform-b3"],
    "Amp":["platform-c1","platform-c2","platform-c3"]
}

我该怎么做?我必须在纯JavaScript中执行此操作

2 个答案:

答案 0 :(得分:2)

让我们为您的案例提供三种不同的方法:

第一个

如果您只想用数据创建json对象,请尝试:

http://jsfiddle.net/csdtesting/tap2xom9/



var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];
var category = ['Guitar', 'Bass', 'Amps'];

var obj = {
  Guitar: platform_a,
  Bass: platform_b,
  Amps: platform_c
};
document.write(JSON.stringify(obj));




第二

如果你想动态创建它,请执行以下操作:

http://jsfiddle.net/csdtesting/tap2xom9/



var category = ['Guitar', 'Bass', 'Amps'];
var platform_a = ['platform-a1', 'platform-a2', 'platform-a3'];
var platform_b = ['platform-b1', 'platform-b2', 'platform-b3'];
var platform_c = ['platform-c1', 'platform-c2', 'platform-c3'];

var FinalObject = {};

FinalObject[category[0]] = platform_a;
FinalObject[category[1]] = platform_b;
FinalObject[category[2]] = platform_c;

document.write(JSON.stringify(FinalObject));




<强>最后

如果你想要更有活力,那么试试这个:

http://jsfiddle.net/csdtesting/kqwz72os/

&#13;
&#13;
var FinalObject = {};

var category = ['Guitar', 'Bass', 'Amps'];
var platforms = {
  platform_a: ['platform-a1', 'platform-a2', 'platform-a3'],
  platform_b: ['platform-b1', 'platform-b2', 'platform-b3'],
  platform_c: ['platform-c1', 'platform-c2', 'platform-c3']
};
for (var i = 0; i < category.length; i++) {
  FinalObject[category[i]] = platforms[Object.keys(platforms)[i]];
}

document.write(JSON.stringify(FinalObject));
&#13;
&#13;
&#13;

希望这有帮助!

答案 1 :(得分:1)

这里没有合理的捷径。你只需要手动完成:

var jsonString = JSON.stringify({
    "Guitar": platform_a,
    "Base": platform_b,
    "Amp": platform_c
});