这个问题似乎很奇怪,但我发现很难转换下面给出的JSON
[
{
"id": 2,
"name": "NP",
"description": "North Pit",
"boxList": [
{
"id": 3,
"name": "Box1",
"description": "First Box",
"locationId": 1,
"benches": [
{
"id": 1,
"name": "Sample Bench",
"description": "Sample Bench"
},
{
"id": 2,
"name": "Sample Bench1",
"description": "Sample Bench1"
}
]
},
{
"id": 6,
"name": "Box2",
"description": "Second Box",
"locationId": 1,
"benches": [
{
"id": 1,
"name": "Sample Bench",
"description": "Sample Bench"
},
{
"id": 2,
"name": "Sample Bench1",
"description": "Sample Bench1"
}
]
}
]
}
]
进入
[
{
"pit": {
"id": 1,
"name": "SouthPit",
"description": "South Description"
},
"boxList": [
{
"boxes": {
"id": 1,
"name": "Sample Box",
"description": "Sample Box"
},
"benchList": [
{
"id": 2,
"name": "Sample Bench1",
"description": "Sample Bench"
}
]
},
{
"boxes": {
"id": 2,
"name": "Sample Box",
"description": "Sample Box"
},
"benchList": [
{
"id": 1,
"name": "Sample Bench",
"description": "Sample Bench"
}
]
}
]
}
]
其中每个物体是一个重复物体,其中可以有多个盒子用于单个坑或多个长凳用于坑。任何人都可以扔一些光。 我试图构建JSON
function constructPitData(data) {
var firstLevel;
var constructedPitDetails = [];
for (var i = 0; i < data.length; i++) {
firstLevel= {
id:data[i].pit.id,
name: data[i].pit.name,
desc: data[i].pit.description,
locId: data[i].pit.mineLocationId,
boxDetails:[]
}
constructedPitDetails.push(firstLevel);
constructBoxDetails(data, firstLevel);
}
}
function constructBoxDetails(data, pit) {
var boxFirstLevel;
var constructedBoxDetails = [];
for (var j = 0; j < data.length; j++) {
if (pit.id === data[j].pit.id) {
var newBox = {
}
}
}
}
答案 0 :(得分:1)
你必须迭代坑和盒子
您的第一步是输入数组中的每个元素
for (var i=0,l=inputarray.length; i<l; i++) {
创建一个新对象
var newpit = {};
并将元素的内容移入其pit
字段
newpit.pit = inputarray[i];
然后将盒子清单移出坑区
newpit.boxList = newpit.pit.boxList;
delete newpit.pit.boxList;
最后将对象推入输出数组
outputarray.push(newpit);
这结束了第1步
现在,您还需要修复boxList,因此为框列表中的每个框编码类似的动作
for (var j=0,n=newpit.pit.boxList.length; j<n; j++) {
创建一个新的框元素
var newbox = {};
并将框清单移至boxes
字段
newbox.boxes = newpit.pit.boxList[j];
以及boxes
和benches
字段
newbox.benches = newbox.boxes.benches;
delete newbox.boxes.benches;
最后推送这个新对象
newpit.boxList.push(newbox);
这结束了第二步
所以,将所有部分放在一起......
var outputarray = [];
for (var i=0,l=inputarray.length; i<l; i++) {
var newpit = {};
newpit.pit = inputarray[i];
newpit.boxList = [];
for (var j=0,n=newpit.pit.boxList.length; j<n; j++) {
var newbox = {};
newbox.boxes = newpit.pit.boxList[j];
newbox.benches = newbox.boxes.benches;
delete newbox.boxes.benches;
newpit.boxList.push(newbox);
}
delete newpit.pit.boxList;
outputarray.push(newpit);
}