从键包含“。”的对象创建json。

时间:2018-11-14 13:38:14

标签: javascript node.js json

如何转换

 {'Address.street': 's street',
  'Address.streetNum': 's street num',
  'Address.npa': 'npa',
  'Address.city': 's city',
  'Address.country': 's country'}

{
Address:{
street: 's street',
streetNum: 's street num'
npa: 'npa'
city:  's city',
country: 's country'
}
}

我正在使用nodejs(v10.12.0)作为后端。

我尝试使用lodash pick,但无法正常工作。

有什么主意吗?

2 个答案:

答案 0 :(得分:0)

为此创建空白数组,然后分配空白对象 然后将对象推入数组

let address=[]
let object=Object.assign({});
object.street='s street';
object.streetNum='s street num'
 ....

address.push(object)

you can console.log(address) 
you will achieve the result

答案 1 :(得分:0)

对于更通用的解决方案,以下是我很快写的内容:

var unflatten = function unflatten(obj) {
    var ret = {};

    //for each flattened key in our original object
    for(var key in obj) {
        if(obj.hasOwnProperty(key)) {
            //split each key into parts separated by '.'
            var parts = key.split('.');

            //keep the last part separate, we'll need it assign our value
            var lastPart = parts.pop();

            //keep a reference to the current child object
            var parent = ret;

            //for each part in our key
            for(var i = 0; i < parts.length; i++) {
                var part = parts[i];

                //only create a new object if it doesn't exist
                if(!parent[part])
                    parent[part] = {};

                //reassign our parent to go one level deeper
                parent = parent[part];
            }

            //finally, assign our original value
            //note that this will overwrite whatever's already there
            parent[lastPart] = obj[key];
        }
    }

    return ret;
};

//usage:
var obj = {
    'foo.bar.baz': 1,
    'foo.qux': 2
};

unflatten(obj);

//returns { foo: { bar: { baz: 1 }, qux: 2 } }

另请参阅@str的评论以了解其他解决方案/讨论