Conversion object by namespace

前端 未结 2 1399
孤城傲影
孤城傲影 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: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; }

提交回复
热议问题