跪求大神,用js或者java循环遍历json数组,实现下面功能,太难了,实在不会,跪求了(6)。

2025-03-22 18:14:33
推荐回答(3个)
回答1:

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;
}

回答2:

回答3:

无外乎就是拼接。。。格式你都清楚了,怎么就拼接不出来