Conversion object by namespace

前端 未结 2 1397
孤城傲影
孤城傲影 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);

    0 讨论(0)
  • 2021-01-19 21:34

    You could use a function for spliting the path to the value and generate new objects for it.

    function setValue(object, path, value) {
        var way = path.split('-'),
            last = way.pop();
    
        way.reduce(function (o, k) {
            return o[k] = o[k] || {};
        }, object)[last] = value;
    }
    
    var object = { 'prop1': 'value.1', 'prop2-subprop1': 'value.2.1', 'prop2-subprop2': 'value.2.2' };
    
    Object.keys(object).forEach(function (key) {
        if (key.indexOf('-') !== -1) {
            setValue(object, key, object[key]);
            delete object[key];
        }
    });
    
    console.log(object);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
提交回复
热议问题