需求:替换数组对象中ids为id,name为label,当children为空数组的时候,删除children子节点
方法一
let list = [{
ids: 1,
name: '蔬菜',
children: []
},
{
ids: 2,
name: '水果',
children: [{
ids: 22,
name: '香蕉',
children: []
}]
}
]
var key = 'childrens'
function parseJson(arr) {
arr = arr.slice()
function toParse(arr) {
arr.forEach(function(item) {
item.label = item.name
delete item.name
if (item.children.length > 0 && Array.isArray(item.children)) {
item[key] = item.children
toParse(item[key])
}
delete item.children
})
return arr
}
return toParse(arr)
}
console.log(parseJson(list))
方法二
let list = [{
ids: 1,
name: '蔬菜',
children: []
},
{
ids: 2,
name: '水果',
children: [{
ids: 22,
name: '香蕉',
children: []
}]
}
]
let stlist = JSON.stringify(list);
stlist = stlist.replace(/\"ids"/g, '"id"');
stlist = stlist.replace(/\"name"/g, '"label"');
stlist = stlist.replace(new RegExp(/(,"children":\[\])/g), '');
console.log(JSON.parse(stlist));