簡體   English   中英

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”和 append 歸為“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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM