javascriptjsondata-objects

How to convert Data Object { "key.subkey": "value" } to { "key" : "subkey": { "value" } }


I want to convert data object from:

let data = {
        "data.name" : "michael",
        "data.email" : "michael@xsx.com",
        "person.gender" : "male"
    }

into

{
    "data" : {
             "name": "michael",
             "email": "michael@xsx.com"
    },
    "person" : {
             "gender": "male"
    }
}

I tried a loop and trying to split key:

let newdata = new Object()
for (const property in datas) {
    let key = `${property.split(".")[0]}`
    let subkey = `${property.split(".")[1]}`
    newdata['key'] =  key;
    newdata['value'] = {subkey: `${datas[property]}`};
    console.log(newdata);
}

The result looks like this:

"data" : {
          "name" : {
                     "michael"
           }
 },
 "data" : {
           "email" : {
                     "michael@xsxx.com"
          }
 },
 "person" : {
            "gender" : {
                     "male"
            }
 }

What's next?


Solution

  • You can use Object.entries to get the key/value pairs from your existing data, then use reduce to convert that into a new object with the split keys forming a nested object:

    const data = {
            "data.name" : "michael",
            "data.email" : "michael@xsx.com",
            "person.gender" : "male"
        }
        
    const result = Object.entries(data).reduce((acc, [key, value]) => {
      [key, subkey] = key.split('.')
      acc[key] = acc[key] || {}
      acc[key][subkey] = value
      return acc
    }, {})
    
    console.log(result)