Javascript数组父子结构

时间:2017-07-13 00:42:27

标签: javascript jquery arrays jquery-select2

我正在尝试将Javascript数组加载到Select2(jQuery替换复选框),如下所示:

$('select').select2({
  data: [
    {
      id: 'value',
      text: 'Text to display'
    },
    // ... more data objects ...
  ]
});

以下是参考:https://select2.github.io/options.html#data

我的数据结构如下:

data: 
    [ 
        { 
            id: "Cheek", 
            text: "Cheek",
            children: [{id: "Cheek Palettes", text: "Cheek Palettes"},
                       {id: "Blush", text: "Blush"},
                       {id: "Bronzer", text: "Bronzer"},
                       {id: "Contour", text: "Contour"},
                       {id: "Highlighter", text:"Highlighter"}],
            id: "Eye", 
            text: "Eye",
            children: [{id: "Eye Palettes", text: "Eye Palettes"},
                       {id: "Mascara", text: "Mascara"},
                       {id: "Eyeliner", text: "Eyeliner"},  
        }
    ]

我创建的选择框仅显示最后一个外出组“Eye”及其子数据。 我在这做错了什么?

1 个答案:

答案 0 :(得分:2)

您的数据结构略有偏差:

data: 
    [ 
        { 
            id: "Cheek", 
            text: "Cheek",
            children: [{id: "Cheek Palettes", text: "Cheek Palettes"},
                   {id: "Blush", text: "Blush"},
                   {id: "Bronzer", text: "Bronzer"},
                   {id: "Contour", text: "Contour"},
                   {id: "Highlighter", text:"Highlighter"}]
        }, // <--- This makes this an array of JSON objects
        { 
            id: "Eye", 
            text: "Eye",
            children: [{id: "Eye Palettes", text: "Eye Palettes"},
                   {id: "Mascara", text: "Mascara"},
                   {id: "Eyeliner", text: "Eyeliner"},
        } // <--- Whereas before, you were replacing the id "Cheek" with "Eye" because JSON only allows one value per key 
    }
]