{"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
}
json是字符串,java 没有提供API遍历json吧,要借助jar包,也就是第三方的API,对json格式的字符串或是java对象之间的转换,比如:一个json格式的字符串,用第三方API(比如gson或jackjson)对json格式字符串进行转换为List类型的,然后用for循环对这list 遍历输出即可,其它对象也是可以的,自定义的实体也行,gson或jackjson有对应的方法能做到
你有两层循环,一个for,一个$.each,肯定会多次
for(var i=0i<data.lengthi++){$("#mytab tbody").append("<tr>")
$.each(data,function(j,k){
alert(k.id)
$("#mytab tbody").append("<td>"+j+"</td>")
$("#mytab tbody").append("<td>"+k.id+"</td>")
$("#mytab tbody").append("<td>"+k.biaoti+"</td>")
$("#mytab tbody").append("<td>"+k.thetime+"</td>")
})
$("#mytab tbody").append("</tr>")
}
改为:
$.each(data,function(j,k){alert(k.id)
$("#mytab tbody").append("<tr>")
$("#mytab tbody").append("<td>"+j+"</td>")
$("#mytab tbody").append("<td>"+k.id+"</td>")
$("#mytab tbody").append("<td>"+k.biaoti+"</td>")
$("#mytab tbody").append("<td>"+k.thetime+"</td>")
$("#mytab tbody").append("</tr>")
})
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)