JSON 数据拆分

这是在数据提交时遇到的问题。

我准备的数据结构是这样的:

    {
        "path": "test",
        "clients": [
            {
                "client": "1.2.2.2;1.1.1.1",
                "Access_Type": 2,
                "name": "test_01"
            },
            {
                "client": "1.2.2.4;1.1.1.4",
                "Access_Type": 1,
                "name": "test_02"
            },
            {
                "client": "1.3.3.3",
                "Access_Type": 1,
                "name": "test_03"
            }
        ]
    }

然而我在提交时需要的数据结构,却是这样的:

    {
        "path": "test",
        "clients": [
            {
                "client": "1.2.2.2",
                "Access_Type": 2,
                "name": "test_01"
            },
            {
                "client": "1.1.1.1",
                "Access_Type": 2,
                "name": "test_01"
            },
            {
                "client": "1.2.2.4",
                "Access_Type": 1,
                "name": "test_02"
            },
            {
                "client": "1.1.1.4",
                "Access_Type": 1,
                "name": "test_02"
            },
            {
                "client": "1.3.3.3",
                "Access_Type": 1,
                "name": "test_03"
            }
        ]
    }

注:client对应的字段,如果是多条并以“;”分隔,则做拆分处理,单条则不处理。

那么如何将数据修改为提交需要的结构?
而对于这种JSON数据结构的拆分,大家有什么解决方案,希望指教一下!

阅读 5.9k
4 个回答

上面是需要的还是下面是需要的。。。

let json =  {
    "path": "test",
    "clients": [
        {
            "client": "1.2.2.2;1.1.1.1",
            "Access_Type": 2,
            "name": "test_01"
        },
        {
            "client": "1.2.2.4;1.1.1.4",
            "Access_Type": 1,
            "name": "test_02"
        },
        {
            "client": "1.3.3.3",
            "Access_Type": 1,
            "name": "test_03"
        }
    ]
}
let clients = [];
json.clients.map(ele1=>{
    let {client,Access_Type,name} = ele1;
    client.split(';').map(ele2=>{
        clients.push({client:ele2,Access_Type,name})
    })
})
json['clients']= clients;
    var bbb = {
        "path": "test",
        "clients":[]
    };
     for(var i in aa.clients){
        var splitarr = aa.clients[i].client.split(";");
            for(var j=0;j<splitarr.length;j++){
                bbb["clients"].push({
                    "client":splitarr[j],
                    "Access_Type":aa.clients[i].Access_Type,
                    "name":aa.clients[i].name
                })
            }       
    }
    console.log(bbb);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题