json javascript 中的多维数组到树结构

json multidimensional array to tree structure in javascript

我有这个 JSON 回复:

    [
{storeWebsites=[
    {website_id=1.0, name=Default Store View}, 
    {website_id=0.0, name=Admin}
    ]}, 
{storeGroups=[
   {website_id=0.0, name=Default, id=0.0}, 
    {website_id=1.0, name=Main Website Store, id=1.0}
    ]}, 
{storeViews=[
    {website_id=1.0, name=Default Store View, code=default, id=1.0}, 
    {website_id=0.0, name=Admin, code=admin, id=0.0}
    ]}
]

我想将“website_id”分组并附加“storeViews.name”。

我正在尝试使用下面的脚本,但我无法将值推送到 var 组中:

     var groups = {};

// .... code to push the values in var groups
 
  $.each(groups, function(key, groups) {
    var $group1 = $("<optgroup>").attr("label", "  " + groups.storeWebsites);
    var $group2 = $("<optgroup>").attr("label", "    " + groups.storeGroups);
  
    groups.storeViews.forEach(function(el) {
      $group2.append(new Option(el.name, el.code));
    });
  
    $('#provider-accounts').append($group1, $group2);
  
  }); 
 
} 

所以我的“id=provider-accounts”应该像下面这样填充:

<optgroup label="Default Store View"></optgroup>
<optgroup label="Main Website Store">
    <option code="default">Default Store View</option>
</optgroup>

    <optgroup label="Admin"></optgroup>
<optgroup label="Default">
    <option code="admin">Admin</option>
</optgroup>

有什么帮助吗?

我认为您交换了以下组:

  • <optgroup label="Default">
  • <optgroup label="Main Website Store">

无论如何,您可以解构您的站点、群组和视图,并在遍历其中之一的同时跟踪它们的索引。

const main = () => {
  const [ {  storeWebsites }, { storeGroups }, { storeViews }] = json;

  $('#provider-accounts').append(storeWebsites.flatMap((site, index) => {
    const
      group = storeGroups[index],
      view = storeViews[index];
    return [
      $('<optgroup>', { label: site.name }),
      $('<optgroup>', { label: group.name })
        .append($('<option>', { code: view.code, text: view.name }))
    ];
  }));
};

const json = [{
  "storeWebsites": [{
    "website_id": 1.0,
    "name": "Default Store View"
  }, {
    "website_id": 0.0,
    "name": "Admin"
  }]
}, {
  "storeGroups": [{
    "website_id": 0.0,
    "name": "Default",
    "id": 0.0
  }, {
    "website_id": 1.0,
    "name": "Main Website Store",
    "id": 1.0
  }]
}, {
  "storeViews": [{
    "website_id": 1.0,
    "name": "Default Store View",
    "code": "default",
    "id": 1.0
  }, {
    "website_id": 0.0,
    "name": "Admin",
    "code": "admin",
    "id": 0.0
  }]
}];

main();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="provider-accounts">
  <!--
  <optgroup label="Default Store View"></optgroup>
  <optgroup label="Default">
    <option code="default">Default Store View</option>
  </optgroup>
  <optgroup label="Admin"></optgroup>
  <optgroup label="Main Website Store">
    <option code="admin">Admin</option>
  </optgroup>
  -->
</select>