javascript - 将嵌套结构添加到平面 json

标签 javascript json

我是 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/

相关文章:

javascript - JSON 解析表情符号 unicode 使我的 React Native 项目崩溃

asp.net - 如何使用 ASP.NET 解析 JSON 字符串?

javascript - Vue Js 在组件模板中迭代不起作用

javascript - jQuery 箭头键功能在我的表格最后一行添加文本框时停止

javascript - 如何使用 angular.js View 刷新页面?

java - 如何从 phonegap 插件获取 android 服务返回消息

c# - 带有期限和日期范围的汇总

JSON 文件的 Python 请求返回 None

php - POST 值不显示在 javascripts 中

json - 如果有 1 个元素,如何防止 ConvertFrom-Json 折叠嵌套数组