我有以下这些数组

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做到这一点

最佳答案

让我们为您的案例介绍三种不同的方法:

第一

如果只想使用数据创建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/



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





希望这可以帮助!

10-07 22:01