跪求大神,用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
展开
 我来答
zero7u
推荐于2017-09-18 · TA获得超过238个赞
知道小有建树答主
回答量:171
采纳率:0%
帮助的人:156万
展开全部
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;
}
ffffohno
2015-02-08 · TA获得超过147个赞
知道答主
回答量:78
采纳率:0%
帮助的人:81.3万
展开全部
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
匿名用户
2015-02-08
展开全部
无外乎就是拼接。。。格式你都清楚了,怎么就拼接不出来
追问
水平菜,可以看看?
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(1)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式