所以我可能会过度思考这个,但我有一个JSON数组,其中包含多层嵌套JSON对象,如下所示:
var OldJSON =
{
"data":{
"shifts":{
"data":[
{
"id":1234,
"entry_time":"2012-06-11 16:06:04",
"attendance_id":1
},
{
"id":4321,
"entry_time":"2014-07-23 17:29:04",
"attendance_id":2
}
]
},
"sites":{
"data":[
{
"id":4321,
"name":"John Doe",
"type":"field",
"bases":{
"data":[
{
"id":1234,
"type":"field",
"active":false
},
{
"id":4321,
"type":"field",
"active":true
}
]
}
},
{
"id":1234,
"name":"Jill Doe",
"type":"field",
"bases":{
"data":[
{
"id":1234,
"type":"field",
"active":false
},
{
"id":4321,
"type":"field",
"active":true
}
]
}
}
]
}
}
}
我想要做的是将'base'对象从'sites'对象中分离出来并重新组织JSON,使它看起来像这样:
var NewJSON =
{
"data":{
"shifts":{
"data":[
{
"id":1234,
"entry_time":"2012-06-11 16:06:04",
"attendance_id":1
},
{
"id":4321,
"entry_time":"2014-07-23 17:29:04",
"attendance_id":2
}
]
},
"sites":{
"data":[
{
"id":4321,
"name":"John Doe",
"type":"field"
},
{
"id":1234,
"name":"Jill Doe",
"type":"field"
}
]
},
"bases":{
"data":[
{
"id":1234,
"type":"field",
"active":false
},
{
"id":4321,
"type":"field",
"active":true
}
]
}
}
}
我在项目中使用Javascript和Angular以及下划线。理想情况下,解决方案将利用这三者之一。我想出来的所有东西看起来都很难看,所以我想知道是否有一种简单的方法可以做我喜欢的这样的事情。
答案 0 :(得分:1)
这段代码怎么样,太丑了?
var data = JSON.parse(/*Your JSON */).data;
var bases = [];
var i;
var sites = data.sites.data;
var len = sites.length;
for (i = 0; i < len; i++) {
var site = sites[i];
var base = site.data.bases;
bases.push(base.date);
delete site.data.bases;
}
data.bases = {data : Array.prototype.concat.apply([], bases) };