我是 javascript 和 json 的新手,我有一个平面 json,在查询表后得到作为响应,结构如下
{
"id": "123",
"First Name": "Jack",
"Last Name": "Jill",
"Mobile phone": "1234567",
"Home Phone": "0123456",
"Address Line1": "xxxx",
"Address Line2": "xxxx",
"City": "New York"
}
我想使用一些 javascript 函数将此平面 json 转换为嵌套 json,并且我想按如下方式转换它。请让我知道如何实现这一目标。
{
"Person": {
"id": "123",
"First Name": "Jack",
"Last Name": "Jill",
"phone": {
"Home Phone": "0123456",
"Mobile Phone": "1234567"
},
"Address": {
"Address Line1": "xxxx",
"Address Line2": "xxxx",
"City": "New York"
}
}
}
最佳答案
基本上,您可以使用对象作为要嵌套的项目的路径。
{ "Mobile phone": "phone", "Home Phone": "phone", "Address Line1": "Address", "Address Line2": "Address", "City": "Address" }
然后检查键是否在对象中,并在必要时使用该值构建新对象。稍后分配原始对象的值。
var object = { "id": "123", "First Name": "Jack", "Last Name": "Jill", "Mobile phone": "1234567", "Home Phone": "0123456", "Address Line1": "xxxx", "Address Line2": "xxxx", "City": "New York" },
groups = { "Mobile phone": "phone", "Home Phone": "phone", "Address Line1": "Address", "Address Line2": "Address", "City": "Address" },
result = {};
Object.keys(object).forEach(function (k) {
if (k in groups) {
result[groups[k]] = result[groups[k]] || {};
result[groups[k]][k] = object[k];
return;
}
result[k] = object[k];
});
console.log(result);
关于javascript - 将嵌套结构添加到平面 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38118555/