JSON剖析-再也不必背景改键名改值名

//声明

function transTOTree(arr, rule) {
    arr.forEach(item => {
        rule.forEach(map => {
            for (let key in map) {
                let newValue = map.oldKey ? item[map.oldKey] : '';
                if (map.newValue) {
                    newValue = map.newValue(newValue);
                }
                item[map.newKey] = newValue;
            }
        })

        if (item.children && item.children.length > 0) {
            transTOTree(item.children, rule);
        }
    });
    return arr;
}

//参数

var params = [{
        oldKey: "name",
        newKey: "title",
        newValue: v => {
            return v;
        }
    },
    {
        oldKey: "is",
        newKey: "checked",
        newValue: v => {
            return v ? 1 : 0;
        }
    }
]

//模仿数据

var oldData = [{
    name: 1,
    is: 1,
    children: [{
        name: 11,
        is: 1,
        children: [{
            name: 1111,
            is: 0,
        }]
    }, {
        name: 12,
        is: 0,
    }]
}, {
    name: 2,
    is: 1,
}]

//挪用

console.log(transTOTree(oldData, params))

//输出

    [{
        title: 1,
        checked: true,
        children: [{
            title: 11,
            checked: true,
            children: [{
                title: 1111,
                checked: false,
            }]
        }, {
            title: 12,
            checked: false,
        }]
    }, {
        title: 2,
        checked: true,
    }]
    原文作者:夏能志
    原文地址: https://segmentfault.com/a/1190000018608082
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞