js 递归修改json无限级key值

var tree = [
    { name: 'node1' },
    { name: 'node2', children: [{ name: 'node-2-1' }, { name: 'node2-2' }] },
    { name: 'node3', children: [{ name: 'node-3-1', children: [{ name: 'node3-1-1' }] }, { name: 'node3-2' }] }
];
var key = 'test'
function parseJson(arr) {
    arr = arr.slice()
    function toParse(arr) {
        arr.forEach(function (item) {
            if (item.children && Array.isArray(item.children)) {
                item[key] = item.children
                toParse(item[key])
            }
            delete item.children
        })
        return arr
    }
    return toParse(arr)
}

console.log(parseJson(tree))

 

posted @ 2018-06-28 18:37  abcByme  阅读(3817)  评论(0编辑  收藏  举报