-3

How can I convert

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

to

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

I am using nodejs (v10.12.0) for backend.

I have trid to use lodash pick, but is not working as expected.

any idea ?

ADyson
  • 57,178
  • 14
  • 51
  • 63
dmx
  • 1,862
  • 3
  • 26
  • 48
  • 3
    these look like JavaScript objects, not JSON strings. Anyway, read the object keys, split them (they're strings) by the dot, and then use the second part as the key names for your inner object. What precisely have you researched or tried so far? The logic doesn't seem hard. – ADyson Nov 14 '18 at 13:39
  • 1
    Possible duplicate of [Convert javascript dot notation object to nested object](https://stackoverflow.com/questions/7793811/convert-javascript-dot-notation-object-to-nested-object) – str Nov 14 '18 at 13:58

2 Answers2

0

for this create blank array then assign blank object then push the object in array

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
0

for a more general solution, here's something I quickly wrote up:

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 } }

see also @str's comment for other solutions/discussion

Andrew Ault
  • 569
  • 3
  • 12