-3

I have a string array like this and trying to build a tree hierarch grouped with . notation. i tried using recursive function and "set" function from lodash but could not get expected result.

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

my expected result is like this

[
   {
      "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"
               }
            ]
         }
      ]
   }
]
Taha Ergun
  • 566
  • 2
  • 7
  • 17
  • 1
    [How to set object property (of object property of..) given its string name in JavaScript?](https://stackoverflow.com/questions/13719593/how-to-set-object-property-of-object-property-of-given-its-string-name-in-ja) – Andreas Jan 21 '20 at 07:30
  • i am not trying to to set objects property, trying to build array tree from dot strings – Taha Ergun Jan 21 '20 at 07:32
  • You're "trying" to get a working solution from us. Read the linked question, and adapt it to your needs. – Andreas Jan 21 '20 at 07:33
  • if could i adapt it for my problem with working solution, i would not ask question in here – Taha Ergun Jan 21 '20 at 07:36

1 Answers1

2

You could split the strings and use the parts as path to the nested array.

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392