Javascript数组父子结构

标签 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”及其子数据。 我在这里做错了什么?

最佳答案

您的数据结构略有偏差:

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 
    }
]

关于Javascript数组父子结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45069684/

相关文章:

Javascript如何从日期时间字符串正确创建DateObject?

javascript - 响应式语音 jquery 插件在循环内不起作用

javascript - PhantomJS page.injectJs 不起作用

javascript - 如何更改 Jquery require_from_group 方法的默认样式?

javascript - Chrome 忽略动态更改元素的相对定位

C++ 间接分配数组值?

javascript - 如何在$.params中动态传递参数数组

jquery - 让视差在 iPad 上运行

python - 如何使用 numpy 数组访问列表的条目而不使用 for 循环

arrays - 如何计算数组元素的运行总计?