Home > Net >  How to convert Data Object { "key.subkey": "value" } to { "key" : &quo
How to convert Data Object { "key.subkey": "value" } to { "key" : &quo

Time:06-12

i want to convert data object from:

let data = {
        "data.name" : "michael",
        "data.email" : "[email protected]",
        "person.gender" : "male"
    }

into

{
    "data" : {
             "name": "michael",
             "email": "[email protected]"
    },
    "person" : {
             "gender": "male"
    }
}

how to doit in javascript? thanks in advanced

update: i already 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" : {
                     "[email protected]"
          }
 },
 "person" : {
            "gender" : {
                     "male"
            }
 }

whats next?

CodePudding user response:

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" : "[email protected]",
        "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)

  • Related