我有以下JSON对象:
var data = [
{
"re_ID": "15.02",
"date": "20.01.2016",
"name": "Opening",
"booking_ID": "4343",
"source": "int",
"meaning": "high",
"date_booking": "31.05.2018"
},
{
"re_ID": "15.02",
"date": "20.01.2016",
"name": "Opening",
"booking_ID": "333",
"source": "int",
"meaning": "high",
"date_booking": "31.04.2018"
},
{
"re_ID": "15.02",
"date": "20.01.2016",
"name": "Opening",
"booking_ID": "434311",
"source": "int",
"meaning": "high",
"date_booking": "31.01.2018"
},
{
"re_ID": "99.33",
"date": "11.08.2013",
"name": "medium",
"booking_ID": "5411",
"source": "ext",
"meaning": "low",
"date_booking": "11.11.2017"
}
]
我需要将其转换为嵌套格式,如下例所示,我可以使用双循环遍历它以从第一个维度获取数据,而使用第二个循环我可以获得第二个维度的信息它:
我需要的结构:
var data = [
{
"re_ID": "15.02",
"date": "20.01.2016",
"name": "Opening"
},
{
"booking_ID": "4343",
"source": "int",
"meaning": "high",
"date_booking": "31.05.2018"
},
{
"booking_ID": "333",
"source": "int",
"meaning": "high",
"date_booking": "31.04.2018"
},
{
"booking_ID": "434311",
"source": "int",
"meaning": "high",
"date_booking": "31.01.2018"
},
{
"re_ID": "99.33",
"date": "11.08.2013",
"name": "medium"
},
{
"booking_ID": "5411",
"source": "ext",
"meaning": "low",
"date_booking": "11.11.2017"
}
];
如何从第一个JSON
构建第二个JSON答案 0 :(得分:0)
好吧,我假设您想要输出的结构实际上并不是您想要的结构,而是将子对象放入数组中。
我还假设如果re_ID相同,那么日期和名称也是一样的。
您只需循环数据数组,然后通过re_ID对转换后的子对象进行分组。完成后,将收集器对象转换回数组:
(注意,如果你需要支持IE,你需要为Array.includes()提供polyfill
function transformJSON(data) {
var collector = {};
var ids = [];
for (var i = 0; i < data.length; i++) {
var reid = data[i].re_ID;
if (!ids.includes(reid)) {
collector[reid] = {
re_ID: reid,
date: data[i].date,
name: data[i].name,
items: []
};
ids.push(reid);
}
collector[reid].items.push({
booking_ID: data[i].booking_ID,
source: data[i].source,
meaning: data[i].meaning,
date_booking: data[i].date_booking
});
}
var output = [];
for (var i = 0; i < ids.length; i++) {
output.push(collector[ids[i]]);
}
return output;
}