跪求大神,用js或者java循环遍历json数组,实现下面功能,太难了,实在不会,跪求了(6)。 200
//如果是java实现,希望不用javabean做,因为json数组里除了first_id,first_name,second_id,second_name,third_...
//如果是java实现,希望不用javabean做,因为json数组里除了first_id,first_name,second_id,second_name,third_id,third_name 其它属性未知,因为属性是配置在数据库,如果加个属性还要修改代码
由于字数限制 未贴代码
这边有pan.baidu.com/s/1o6p4OaA 展开
由于字数限制 未贴代码
这边有pan.baidu.com/s/1o6p4OaA 展开
3个回答
展开全部
var origin = [
{"first_id":1,"first_name":"中学","second_id":"1-1","second_name":"一年级","third_id":"1-1-1","third_name":"一年级一班","people":10,"age":10,"parent":5},
{"first_id":1,"first_name":"中学","second_id":"1-1","second_name":"一年级","third_id":"1-1-2","third_name":"一年级二班","people":11,"age":10,"parent":5},
{"first_id":1,"first_name":"中学","second_id":"1-2","second_name":"二年级","third_id":"1-2-1","third_name":"二年级一班","people":20,"age":10,"parent":5},
{"first_id":1,"first_name":"中学","second_id":"1-2","second_name":"二年级","third_id":"1-2-2","third_name":"二年级二班","people":21,"age":10,"parent":5},
{"first_id":2,"first_name":"高中","second_id":"2-1","second_name":"一年级","third_id":"2-1-1","third_name":"一年级一班","people":31,"age":10,"parent":5}
];
var finalData = []; // 最终的数据
transferData(); // 数据转换
console.log(finalData, JSON.stringify(finalData));
function transferData() {
origin.forEach(function(n) {
var first = getRecordById(n.first_id, finalData);
if (first) {
first.age += n.age;
first.parent += n.parent;
first.people += n.people;
var second = getRecordById(n.second_id, first.children);
if (second) {
second.age += n.age;
second.parent += n.parent;
second.people += n.people;
var third = getRecordById(n.third_id, second.children);
if (third) {
// 这里应该不会存在
} else {
second.children.push({
id: n.third_id,
name: n.third_name,
age: n.age,
parent: n.parent,
people: n.people
});
}
} else {
first.children.push({
id: n.second_id,
name: n.second_name,
age: n.age,
parent: n.parent,
people: n.people,
children: [{
id: n.third_id,
name: n.third_name,
age: n.age,
parent: n.parent,
people: n.people
}]
});
}
} else {
finalData.push({
id: n.first_id,
name: n.first_name,
age: n.age,
parent: n.parent,
people: n.people,
children: [{
id: n.second_id,
name: n.second_name,
age: n.age,
parent: n.parent,
people: n.people,
children: [{
id: n.third_id,
name: n.third_name,
age: n.age,
parent: n.parent,
people: n.people
}]
}]
});
}
});
}
function getRecordById(id, data) {
for (var i = 0, n = data.length; i < n; i++) {
if (data[i].id == id) return data[i];
}
return null;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询