Conversion object by namespace

前端 未结 2 1398
孤城傲影
孤城傲影 2021-01-19 21:02

I need to convert \"flat object\" like this (input data):

{
   \'prop1\': \'value.1\',
   \'prop2-subprop1\': \'value.2.1\',
   \'prop2-subprop2\': \'value.2         


        
2条回答
  •  迷失自我
    2021-01-19 21:23

    var input = {
        "property1": "value1",
        "property2.property3": "value2",
        "property2.property7": "value4",
        "property4.property5.property6.property8": "value3"
    }
    
    function addProp(obj, path, pathValue) {
        var pathArray = path.split('.');
        pathArray.reduce(function (acc, value, index) {
            if (index === pathArray.length - 1) {
                acc[value] = pathValue;
                return acc;
            } else if (acc[value]) {
                if (typeof acc[value] === "object" && index !== pathArray.length - 1) {
                    return acc[value];
                } else {
                    var child = {};
                    acc[value] = child;
                    return child;
                }
            } else {
                var child = {};
                acc[value] = child;
                return child;
            }
        }, obj);
    }
    
    var keys = Object.keys(input);
    var output = {};
    keys.forEach(function (k) {
        addProp(output, k, input[k]);
    });
    console.log(output);

提交回复
热议问题