如何将数据对象 { "key.subkey" : "value" } 转换为 { "key" : "subkey" : { "value" } }



我想转换数据对象:

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

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

我尝试了一个循环,并试图分割密钥:

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

结果如下:

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

接下来是什么?

您可以使用Object.entries从现有数据中获取键/值对,然后使用reduce将其转换为具有拆分键形成嵌套对象的新对象:

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)

相关内容

  • 没有找到相关文章

最新更新