这是我的JSON数组格式
[
[
"1234",
[
"Name11"
],
"4567",
[
"Name12"
],
"7890",
[
"Name13"
]
],
[
"1234",
[
"Name21"
],
"4567",
[
"Name22"
],
"7890",
[
"Name23"
]
]
]
" 1234"," 4567"和" 7890"是我的ID和" Name11"," Name12"," Name13"," Name21"," Name22"和#34;名称23"是每个相应ID的值。 JSON数组包含两个记录,如上所示。现在我需要转换以下JSON格式....
[
{
"1234":"Name11",
"4567":"Name12",
"7890":"Name13"
},
{
"1234":"Name21",
"4567":"Name22",
"7890":"Name23"
}
]
请帮帮我,我该如何构建上面提到的JSON数组格式。
答案 0 :(得分:0)
使用纯javascript:
var src = [
[
"1234",
[
"Name11"
],
"4567",
[
"Name12"
],
"7890",
[
"Name13"
]
],
[
"1234",
[
"Name21"
],
"4567",
[
"Name22"
],
"7890",
[
"Name23"
]
]
]
var newObj = []
for(var i = 0; i< src.length; i++){
var item = {}
for(var j = 0; j<src[i].length; j++){
if(j%2 === 0){
item[src[i][j]] = ""
}else{
item[src[i][j-1]] = src[i][j][0]
}
}
newObj.push(item)
}
答案 1 :(得分:0)
您可以使用以下代码执行此操作(请参阅下面的代码段):
var res = src.map(function(a){
var arr = [];
for(var i=0;i<a.length/2;i++) {
var item = {};
item[a[i*2]] = a[i*2+1][0];
arr.push(item);
};
return arr;
});
var src = [
[
"1234",
[
"Name11"
],
"4567",
[
"Name12"
],
"7890",
[
"Name13"
]
],
[
"1234",
[
"Name21"
],
"4567",
[
"Name22"
],
"7890",
[
"Name23"
]
]
];
var res = src.map(function(a){
var arr = [];
for(var i=0;i<a.length/2;i++) {
var item = {};
item[a[i*2]] = a[i*2+1][0];
arr.push(item);
};
return arr;
});
document.getElementById("res").textContent = JSON.stringify(res);
<div id="res"></div>