skip to Main Content

I need get path with object jeys of JS. Function must pass thrught all object, even if he will deep.

Input data

    {
      tree1: {
        node1: 'valOfnode1',
        node2: 'valOfnode2',
        node3: 'valOfnode3',
        node4: {
          node5: 'valOfnode5',
          node6: 'valOfnode6',
          node7: {
            node8: 'valOfnode8',
            node9: 'surprize!',
          },
        }
      }
    };

Output data

    [
      ['tree1.node1': 'valOfnode1'],
      ['tree1.node2': 'valOfnode2'],
      ['tree1.node3': 'valOfnode3'],
      ['tree1.node4.node5': 'valOfnode5'],
      ['tree1.node4.node6': 'valOfNode6'],
      ['tree1.node4.node7.node8': 'valOfNode8'],
      ['tree1.node4.node7.node9': 'surprize!'], 
    ]

I tryed made a function, but in result i get all paths.
It is a my function. This function need for get depth of every path.

    const sortObject = (obj) => {
      const arr = [];
      const entries = Object.entries(obj);
      let headKey;
      
      const iter = (data) => {
        const keys = Object.keys(data);
        keys.forEach((key) => {
          if (typeof data[keys] !== 'object') {
            arr.push(`${headKey}.${keys}`);
            console.log(arr);
          } if (typeof data[keys] === 'object') {
            return iter(data[keys]);
          }
        });
      }
      
      return entries.forEach(([key, value]) => {
        headKey = key;
        if (typeof value === 'object') {
          return iter(value);
        }
      })
      console.log(arr);
    }

3

Answers


  1. function getObjectPaths(obj, parentKey = '') {
      let paths = [];
    
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          const value = obj[key];
          const currentKey = parentKey ? `${parentKey}.${key}` : key;
    
          if (typeof value === 'object' && value !== null) {
            const nestedPaths = getObjectPaths(value, currentKey);
            paths = paths.concat(nestedPaths);
          } else {
            paths.push([currentKey, value]);
          }
        }
      }
    
      return paths;
    }
    
    const data = {
      tree1: {
        node1: 'valOfnode1',
        node2: 'valOfnode2',
        node3: 'valOfnode3',
        node4: {
          node5: 'valOfnode5',
          node6: 'valOfnode6',
          node7: {
            node8: 'valOfnode8',
            node9: 'surprize!',
          },
        },
      },
    };
    
    const result = getObjectPaths(data);
    console.log(result);
    
    Login or Signup to reply.
  2. Use an array variable stack to store objects and their prefixes. do a while loop as long as there are objects in the stack. each iteration pop an object and its prefix from the stack, then loop over the properties of the object and check if the value is another object, if so push it onto the stack and update the prefix. Otherwise add the key-value pair with the concatenated prefix flattened key-value pairs:

    const tree = {
      tree1: {
        node1: 'valOfnode1',
        node2: 'valOfnode2',
        node3: 'valOfnode3',
        node4: {
          node5: 'valOfnode5',
          node6: 'valOfnode6',
          node7: {
            node8: 'valOfnode8',
            node9: 'surprize!',
          },
        },
      },
    };
    
    const stack = [];
    const result = [];
    
    stack.push([tree, '']);// Push initial object with an empty prefix
    while (stack.length > 0) {
      const [currObj, prefix] = stack.pop();
      for (let key in currObj) {
        const value = currObj[key];
        if (typeof value === 'object') {
          stack.push([value, prefix + key + '.']);
        } else {
          result.push([prefix + key, value]);
        }
      }
    }
    console.log(result);
    Login or Signup to reply.
  3. Recursively walk by object keys and collect the paths:

    const obj = {
        tree1: {
            node1: 'valOfnode1',
            node2: 'valOfnode2',
            node3: 'valOfnode3',
            node4: {
                node5: 'valOfnode5',
                node6: 'valOfnode6',
                node7: {
                    node8: 'valOfnode8',
                    node9: 'surprize!',
                },
            }
        }
    };
    
    const paths = [];
    
    walk(obj);
    
    console.log(JSON.stringify(paths));
    
    function walk(obj, path = '') {
        for (const k in obj) {
            const key = path + (path ? '.' : '') + k;
            if (typeof obj[k] === 'object') {
                walk(obj[k], key);
                continue;
            }
            paths.push([key, obj[k]]);
        }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search