通过Javascript遍历复杂的JSON对象的最简单方法

我正在使用具有一些奇怪结构的JSON数据,例如:

{

"RESULT":

{

"COLUMNS": ["ID","name","ENABLED","perms","vcenabled","vcvalue","checkenabled","checkvalue","indxenabled","indxvalue"],

"DATA": [

[7,"Site-A", 1, "1,2", 1, 1, 1, 0, 0, 0],

[15,"Site-B", 1, "1,2,3,4", 1, 1, 1, 0, 0, 0]

]

},

"ERROR": 0

}

我想创建一些JavaScript,将这些数据重组为适当的JSON结构,以使“列”数组值成为“数据”数组值的键。因此,在运行JS进程后,数据类似于以下内容:

[

{"ID":7,"name":"Site-A","ENABLED":1,"perms":"1,2","vcenabled":1,"vcvalue":1,"checkenabled":1,"checkvalue":1,"indxenabled":1,"indxvalue":1},

{"ID":15,"name":"Site-B","ENABLED":1,"perms":"1,2","vcenabled":1,"vcvalue":1,"checkenabled":1,"checkvalue":1,"indxenabled":1,"indxvalue":1}

]

完成JSON重组的JavaScript最佳做法是什么?我可以使用JQuery,Foundation JS等JS框架完成此任务吗?

回答:

newjson是您的新对象,j是您的json,

代码非常快,因为它缓存了很多信息,并且不使用push。

而且由于它是纯JavaScript,因此比所有库都快。

var j={

"RESULT":{

"COLUMNS":[

"ID",

"name",

"ENABLED",

"perms",

"vcenabled",

"vcvalue",

"checkenabled",

"checkvalue",

"indxenabled",

"indxvalue"

],

"DATA":[

[7,"Site-A", 1, "1,2", 1, 1, 1, 0, 0, 0],

[15,"Site-B", 1, "1,2,3,4", 1, 1, 1, 0, 0, 0]

]

},

"ERROR": 0

}

var newjson=[],d=j.RESULT.COLUMNS.length;

for(var a=0,b=j.RESULT.DATA.length;a<b;a++){

for(var c=0,tmpObj={};c<d;c++){

tmpObj[j.RESULT.COLUMNS[c]]=j.RESULT.DATA[a][c];

}

newjson[a]=tmpObj;

}

console.log(newjson);

根据Bergi的响应,您还可以使用while–循环。

var orig={

"RESULT":{

"COLUMNS":[

"ID",

"name",

"ENABLED",

"perms",

"vcenabled",

"vcvalue",

"checkenabled",

"checkvalue",

"indxenabled",

"indxvalue"

],

"DATA":[

[7,"Site-A", 1, "1,2", 1, 1, 1, 0, 0, 0],

[15,"Site-B", 1, "1,2,3,4", 1, 1, 1, 0, 0, 0]

]

},

"ERROR": 0

}

var formatted = [],

data = orig.RESULT.DATA,

cols = orig.RESULT.COLUMNS,

l = cols.length,

f = data.length;

while (f--) {

var d = data[f],

o = {},

g = l;

while (g--) {

o[cols[g]] = d[g];

}

formatted[f] = o;

}

以上是 通过Javascript遍历复杂的JSON对象的最简单方法 的全部内容, 来源链接: utcz.com/qa/415901.html

回到顶部