-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"
               }
            ]
         }
      ]
   }
]
4
  • 1
    How to set object property (of object property of..) given its string name in JavaScript? Commented Jan 21, 2020 at 7:30
  • i am not trying to to set objects property, trying to build array tree from dot strings Commented Jan 21, 2020 at 7:32
  • You're "trying" to get a working solution from us. Read the linked question, and adapt it to your needs. Commented Jan 21, 2020 at 7:33
  • if could i adapt it for my problem with working solution, i would not ask question in here Commented Jan 21, 2020 at 7:36

1 Answer 1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.