【问题标题】:JS: Convert dot string array to object tree [duplicate]JS:将点字符串数组转换为对象树
【发布时间】:2020-05-07 05:10:22
【问题描述】:

我有一个这样的字符串数组,并试图构建一个与 .符号。我尝试使用 lodash 中的递归函数和“set”函数,但无法获得预期的结果。

let stringArray = [
  'catalog.product.name', 
  'catalog.product.description', 
  'catalog.product.status', 
  'catalog.product_attribute_set.name'
  'catalog.product_attribute_set.type'
]

我的预期结果是这样的

[
   {
      "value":"catalog",
      "label":"catalog",
      "children":[
         {
            "value":"product",
            "label":"product",
            "children":[
               {
                  "value":"name",
                  "label":"name"
               },
               {
                  "value":"description",
                  "label":"description"
               },
               {
                  "value":"status",
                  "label":"status"
               }
            ]
         },
         {
            "value":"product_attribute_set",
            "label":"product_attribute_set",
            "children":[
               {
                  "value":"name",
                  "label":"name"
               },
               {
                  "value":"type",
                  "label":"type"
               }
            ]
         }
      ]
   }
]

【问题讨论】:

标签: javascript arrays multidimensional-array tree


【解决方案1】:

您可以拆分字符串并将这些部分用作嵌套数组的路径。

var array = ['catalog.product.name', 'catalog.product.description', 'catalog.product.status', 'catalog.product_attribute_set.name', 'catalog.product_attribute_set.type'],
    result = [];

array.forEach(s => s
    .split('.')
    .reduce((object, value) => {
        var item = (object.children = object.children || []).find(q => q.value === value);
        if (!item) object.children.push(item = { value, label: value })
        return item;
    }, { children: result })
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    猜你喜欢
    • 2019-12-17
    • 2023-01-12
    • 2019-03-14
    • 2012-05-08
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多