json多维数组到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},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
  },"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>