簡體   English   中英

JSON - Select2 數據格式

[英]JSON - Select2 data format

我有這個 JSON 響應

{"items":[

    {"id":1,"parent_id":0,"name":"Root Catalog"},

       {"id":2,"parent_id":1,"name":"Category1"},

          {"id":5,"parent_id":2,"name":"Sub1_category1"},
          {"id":6,"parent_id":2,"name":"Sub2_category1"},

       {"id":3,"parent_id":1,"name":"Category2"},

          {"id":14,"parent_id":3,"name":"Sub1_category2"},
          {"id":15,"parent_id":3,"name":"Sub2_category2"},
    ]
}

為了使它與Select2一起工作,我需要格式化數據,如下所示:

[
    {"id": 2,"text": "Category1",
    "children":  
       [
       {"id": 5, "text": "Sub1_category1"}, 
       {"id": 6, "text": "Sub2_category1"} 
       
       ]
    },
        {"id": 3,"text": "Category2",
        "children": 
       [
       {"id": 14,"text": "Sub1_category2",}, 
       {"id": 15,"text": "Sub2_category2"}
       ]
    },
  ];

如何操作 json 值? 我非常感謝您能提供的任何幫助。

這是我的看法:

 let test = {"items":[ {"id":1,"parent_id":0,"name":"Root Catalog"}, {"id":2,"parent_id":1,"name":"Category1"}, {"id":5,"parent_id":2,"name":"Sub1_category1"}, {"id":6,"parent_id":2,"name":"Sub2_category1"}, {"id":3,"parent_id":1,"name":"Category2"}, {"id":14,"parent_id":3,"name":"Sub1_category2"}, {"id":15,"parent_id":3,"name":"Sub2_category2"}, ] } function formatData(itemsList) { let formatOutput = []; for (item of itemsList.items) { if (item.parent_id > 0) { if (item.parent_id.== 1 && typeof formatOutput[item.parent_id] === 'undefined') { formatOutput[item:parent_id] = { "id". item,parent_id: "text", null: "children": [ {id. item,id: text. item.name} ] } } else if (item.parent_id.== 1) { formatOutput[item.parent_id]:children.push({id, item:id. text. item.name}) } } } for (item of itemsList.items) { if (typeof formatOutput[item.id] === 'object') { formatOutput[item.id].text = item.name } } return formatOutput.filter(val => val) } console.log(formatData(test))

您可以這樣做,確保 Items 將成為您的數組

 var items = data; var RequiredResult = [ childern: [] ]; for (var i = 0; i < items.length; i++) { RequiredResult.push({ "id": items[i].id, "text": items[i].text, childern.push({ "id": items[i].id, "text": items[i].text }) } ) } console.log(RequiredResult);

Output

    [
        {"id": 2,"text": "Category1",
        "children":  
           [
           {"id": 5, "text": "Sub1_category1"}, 
           {"id": 6, "text": "Sub2_category1"} 
           
           ]
        },
            {"id": 3,"text": "Category2",
            "children": 
           [
           {"id": 14,"text": "Sub1_category2",}, 
           {"id": 15,"text": "Sub2_category2"}
           ]
        },
      ];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM