{"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
}
java可以使用JSONObject和JSONArray来 *** 作json对象和json数组,具体用法如下1:java对象与json串转换:
java对象—json串:
JSONObject JSONStr = JSONObject.fromObject(object)
String str = JSONStr.toString()
json串—java对象:
JSONObject jsonObject = JSONObject.fromObject( jsonString )
Object pojo = JSONObject.toBean(jsonObject,pojoCalss)
2:java数组对象与json串转换:
java数组—json串:
JSONArray arrayStr = JSONArray.fromObject(List<?>)
String str = arrayStr.toString()
json串—java数组:
JSONArray array = JSONArray.fromObject(str)
List<?>list = JSONArray.toList(array, ?.class)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)