简体   繁体   中英

How to build tree from path

I need to convert some path to a tree object. the path should represent the tree with the following requirements:

  1. for '.items.properties' after the key, the type should be array of objects.
  2. for '.items' after the key, the type should be an array.
  3. for '.properties' after the key, the type should be an object.

for example for this path: 'key1.items.properties.key2.items.properties.key3.items'

key1 is the key and the type is array of object.

This is the final result that I expect to get from this path

'key1.items.properties.key2.items.properties.key3.items' // path

//expected
{
  key1: [
    {
      key2:[
        {
          key3:[]
        }
      ]
    }
  ]
}

Edit: I know how to convert this path to this data structure with 'json-pointer':

{
  key1: {
      key2:{
        {
          key3:[]
        }
      }
    }
}

So if you have a way to convert my data structure to the expected it's could help.

You could take the parts and look ahead for a key with a following 'items' string, the create a new property with an empty array.

For 'properties' create a new object and push it to the temporary array.

 var string = 'key1.items.properties.key2.items.properties.key3.items', parts = string.split('.'), result = {}, temp = result; for (let i = 0; i < parts.length; i++) { if (parts[i] === 'properties') { let object = {}; temp.push(object); temp = object; continue; } if (parts[i + 1] === 'items') { let items = []; temp[parts[i]] = items; i++; temp = items; continue; } } console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM