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 值? 非常感谢您提供的任何帮助。

你可以这样做,确保 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);

输出

    [
        {"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"}
           ]
        },
      ];

这是我的看法:

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))