[
{
"type": "姚庄镇",
"sum": 1,
"childrenList": [
{
"type": "办结",
"sum": 1,
"childrenList": null
}
]
},
{
"type": "西塘镇",
"sum": 11,
"childrenList": [
{
"type": "处置中",
"sum": 1,
"childrenList": null
},
{
"type": "办结",
"sum": 10,
"childrenList": null
}
]
},
{
"type": "陶庄镇",
"sum": 3,
"childrenList": [
{
"type": "处置中",
"sum": 1,
"childrenList": null
},
{
"type": "办结",
"sum": 2,
"childrenList": null
}
]
},
{
"type": "天凝镇",
"sum": 2,
"childrenList": [
{
"type": "办结",
"sum": 2,
"childrenList": null
}
]
}
]
[
{
"x": "陶庄",
"y": "3",
"s": "总数"
},
{
"x": "陶庄",
"y": "1",
"s": "处置中"
},
{
"x": "陶庄",
"y": "2",
"s": "已办结"
},
{
"x": "西塘",
"y": "11",
"s": "总数"
},
{
"x": "西塘",
"y": "1",
"s": "处置中"
},
{
"x": "西塘",
"y": "10",
"s": "已办结"
},
{
"x": "姚庄",
"y": "1",
"s": "总数"
},
{
"x": "姚庄",
"y": "0",
"s": "处置中"
},
{
"x": "姚庄",
"y": "1",
"s": "已办结"
},
{
"x": "天凝",
"y": "2",
"s": "总数"
},
{
"x": "天凝",
"y": "0",
"s": "处置中"
},
{
"x": "天凝",
"y": "2",
"s": "已办结"
},
]
上面的数组想要整理成下面的数组 应该怎么做
var nejosn = [];
var nejosn1 = [];
var json = "[{\"type\":\"姚庄镇\",\"sum\":1,\"childrenList\":[{\"type\":\"办结\",\"sum\":1,\"childrenList\":null}]},{\"type\":\"西塘镇\",\"sum\":11,\"childrenList\":[{\"type\":\"处置中\",\"sum\":1,\"childrenList\":null},{\"type\":\"办结\",\"sum\":10,\"childrenList\":null}]},{\"type\":\"陶庄镇\",\"sum\":3,\"childrenList\":[{\"type\":\"处置中\",\"sum\":1,\"childrenList\":null},{\"type\":\"办结\",\"sum\":2,\"childrenList\":null}]},{\"type\":\"天凝镇\",\"sum\":2,\"childrenList\":[{\"type\":\"办结\",\"sum\":2,\"childrenList\":null}]}]";
var ObjData = eval('(' + json + ')');
for (var i = 0; i < ObjData.length; i++) {
var addjson = { "x": "" + ObjData[i].type + "", "y": "" + ObjData[i].sum + "", "s": "总数" };
for (var j = 0; j < ObjData[i].childrenList.length; j++) {
var addjson1 = { "x": "" + ObjData[i].type + "", "y": "" + ObjData[i].childrenList[j].sum + "", "s": "" + ObjData[i].childrenList[j].type + "" };
nejosn1.push(addjson1);
}
nejosn.push(addjson);
}
var c = nejosn1.concat(nejosn);
console.log(c.sort((a, b) => a.x.localeCompare(b.x)))
递归
let data = [
{
"type": "姚庄镇",
"sum": 1,
"childrenList": [
{
"type": "办结",
"sum": 1,
"childrenList": null
}
]
},
{
"type": "西塘镇",
"sum": 11,
"childrenList": [
{
"type": "处置中",
"sum": 1,
"childrenList": null
},
{
"type": "办结",
"sum": 10,
"childrenList": null
}
]
},
{
"type": "陶庄镇",
"sum": 3,
"childrenList": [
{
"type": "处置中",
"sum": 1,
"childrenList": null
},
{
"type": "办结",
"sum": 2,
"childrenList": null
}
]
},
{
"type": "天凝镇",
"sum": 2,
"childrenList": [
{
"type": "办结",
"sum": 2,
"childrenList": null
}
]
}
];
let flatarr = flatData(data);
console.log(flatarr)
function flatData(data) {
let arr = [];
if (data) {
data.map((item) => {
// let obj = {};
// obj.x = item.type;
// obj.y = item.sum;
// obj.s = item.type;
if (item && item.childrenList && item.childrenList.length > 0) {
item.childrenList.map((item1) => {
let obj1={}
obj1.x = item.type;
obj1.y = item1.sum;
obj1.s = item1.type;
arr.push(obj1);
})
}
// arr.push(obj);
});
}
return arr;
}