将嵌套结构添加到平面json

时间:2016-06-30 09:07:23

标签: 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"
        }
    }
}

2 个答案:

答案 0 :(得分:0)

没有自动方法可以做到这一点。您可能想要做的是围绕这条道路:

var flatJSONObject = {"id":"123","First Name": "Jack", "Last Name":"Jill", 
"Mobile phone":"1234567", "Home Phone":"0123456","Address Line1":"xxxx",
 "Address Line2":"xxxx", "City":"New York"};

var newJSONObject = {
    person: {
    id: flatJSONObject.id,
    firstName: flatJSONObject['First Name'],
    lastName: flatJSONObject['Last Name'],
    phone:{
        homePhone: flatJSONObject['Home Phone'],
      mobilePhone: flatJSONObject['Mobile phone']
    },
    address: {
        addressLine1: flatJSONObject['Address Line1'],
        addressLine2: flatJSONObject['Address Line2'],
      city: flatJSONObject.City
    }
  }
} 

console.log(newJSONObject);

答案 1 :(得分:0)

基本上你可以使用一个对象来嵌套项目的路径。

{
    "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);