【JS】js递归修改json数据
将所有键名为list变成children,键名为name变成label怎么弄,写了半天只改到了第二层,第三层获取的数组里都是undefined,求大神帮忙
回答
这个tree看起来格式很规范,所以转成字符串替换下再转 JSON 得了:
JSON.parse(JSON.stringify(tree).replace(/list:/g, 'children:').replace(/name:/g, 'label:'));
从思考到写完只用不到三分钟。
而递归写起来多麻烦,你看:
const keyChange = (objTree) => { for(let key in objTree){
if(objTree.hasOwnProperty(key)){
const current = objTree[key];
if(current instanceof Object){
keyChange(current )
}
if(key === 'list'){
objTree['children'] = current;
delete objTree['list'];
} else if(key === 'name'){
objTree['label'] = current;
delete objTree['name'];
}
}
}
return null;
}
PS. 以上代码未经测试,如有需要,请自行测试、改良。
function changeName(a) { var isArray = function(b) {
return Object.prototype.toString.call(b) == '[object Array]';
};
if (isArray(a) && a.length) {
for (let i = 0; i < a.length; i++) {
if (a[i].name) {
a[i].label = a[i].name;
delete a[i].name;
}
if (a[i].list) {
a[i].children = a[i].list;
delete a[i].list;
changeName(a[i].children);
}
}
}
}
changeName(tree);
const tree = [ {
name: 'node1',
id: '1-1'
},
{
name: 'node2',
list: [
{
name: 'node-2-1',
id: '2-1'
},
{
name: 'node2-2',
id: '2-2'
}
]
},
{
name: 'node3',
list: [
{
name: 'node-3-1',
id: '3-1',
list: [
{
name: 'node3-1-1',
id: '3-1-1'
}
]
},
{
name: 'node3-2',
id: '3-2'
}
]
}
]
function trans (tree) {
tree.forEach(item => {
if (item.list) {
item.children = item.list
delete item.list
trans(item.children)
}
if (item.name !== undefined) {
item.label = item.name
delete item.name
}
})
}
trans(tree)
console.log(tree)
以上是 【JS】js递归修改json数据 的全部内容, 来源链接: utcz.com/a/89869.html