Sarkis Arutiunian Sarkis Arutiunian - 2 months ago 16
Javascript Question

Object props, combine in object prop

For example we have object as below:

let data = {
firstName: '',
lastName: '',
"other.ref": '',
"other.ref1": '',
"other.ref2": '',
"other.ref3": '',
"other1.ref": '',
"other1.ref1": '',
"other1.ref2": '',
"other1.ref3": ''
}


and I want get next object:

let data = {
firstName: '',
lastName: '',
other: {
ref: '',
ref1: '',
ref2: '',
ref3: ''
},
other1: {
ref: '',
ref1: '',
ref2: '',
ref3: ''
}
}


What is maximum performance way to do that?
Thanks.

Answer

You could iterate the keys and split them. If more than one element in the array is found, generate a new object, if necessary. Then assign the value and delete the old property.

var data = { firstName: '', lastName: '', "other.ref": '', "other.ref1": '', "other.ref2": '', "other.ref3": '', "other1.ref": '', "other1.ref1": '', "other1.ref2": '', "other1.ref3": '' };

Object.keys(data).forEach(function (k) {
    var path = k.split('.'),
        last = path.pop();

    if (path.length) {
        path.reduce((r, a) => r[a] = r[a] || {}, data)[last] = data[k];
        delete data[k];
    }
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments