//分层级,数组扁平化处理
let json = [
{
checked: true,
key: "tgi_popu_base_age#1979:1975",
leaf: 1,
onekey: "tgi_popu",
onename: "人口属性",
parentKey: null,
rank: 0,
skey: "tgi_popu_base_age",
sname: "年龄",
text: "40—44岁",
twokey: "tgi_popu_base",
twoname: "基本信息",
uiType: "text",
},
{
checked: true,
key: "tgi_popu_base_age#1969:1938",
leaf: 1,
onekey: "tgi_popu",
onename: "dd属性",
parentKey: null,
rank: 0,
skey: "tgi_popu_base_age",
sname: "年龄",
text: "50岁及以上",
twokey: "tgi_popu_base",
twoname: "基本信息",
uiType: "text",
},{
checked: true,
key: "tgi_popu_base_age#2008:2005",
leaf: 1,
onekey: "tgi_popu",
onename: "人口属性",
parentKey: null,
rank: 0,
skey: "tgi_popu_base_age",
sname: "年龄",
text: "14岁及以下",
twokey: "tgi_popu_base",
twoname: "基本信息",
uiType: "text",
},
{
checked: true,
key: "tgi_popu_base_gender#f",
leaf: 1,
onekey: "tgi_popu",
onename: "人口属性",
parentKey: "tgi_popu_base_gender",
rank: 0,
skey: "tgi_popu_base_gender",
sname: "性别",
text: "女",
twokey: "tgi_popu_base",
twoname: "基本信息",
uiType: "text",
},
{
checked: true,
key: "tgi_popu_work_type#1",
leaf: 1,
onekey: "tgi_popu",
onename: "人口属性",
parentKey: "tgi_popu_work_type",
rank: 0,
skey: "tgi_popu_work_type",
sname: "所属行业类型",
text: "蓝领",
twokey: "tgi_popu_work",
twoname: "工作状况",
uiType: "text",
},{
checked: true,
key: "tgi_popu_work_type#8",
leaf: 1,
onekey: "tgi_popu",
onename: "人口属性",
parentKey: "tgi_popu_work_type",
rank: 0,
skey: "tgi_popu_work_type",
sname: "所属行业类型",
text: "丽人",
twokey: "tgi_popu_work",
twoname: "工作状况",
uiType: "text"
}
]
function jsonMerge(jsonArr,keyArr){
let newJson = [] //合并好的数据都放在这个数组里
jsonArr.forEach((itemJson,indexJson)=>{
let mark = -1
let finded = newJson.find((itemFind, indexFind) => {
if (itemFind[keyArr[0]] === itemJson[keyArr[0]]) {
mark = indexFind
return itemFind[keyArr[0]] === itemJson[keyArr[0]]
}
})
if(!finded){
let value = {}
value[keyArr[0]] = itemJson[keyArr[0]]
value['data'] = []
let info = {}
for(let i in itemJson){
if(i!==keyArr[0]){
info[i] = itemJson[i]
}
}
value['data'].push(info)
newJson.push(value)
}else{
let info = {}
for(let i in itemJson){
if(i!==keyArr[0]){
info[i] = itemJson[i]
}
}
newJson[mark]['data'].push(info)
}
})
// 递归的条件是不断的缩减keyArr的length,每次都去除第零个,直到为0
if(keyArr.length === 1){
return newJson
}else{
return newJson.map((itemInfo)=>{
let newKeyArr = []
keyArr.forEach((item,index)=>{
if(index>0){
newKeyArr.push(item)
}
})
return{
[keyArr[0]]:itemInfo[keyArr[0]],
'data':jsonMerge(itemInfo['data'],newKeyArr)
}
})
}
}
console.log(jsonMerge(json,['onename','twoname','sname']))