0

I trying to generate all possible paths of the given json object. Some how I generated the paths but I want my final array in a flatten manner (no nested arrays inside the final array). I tried speading the array, but the final array contains some nested arrays. I want to have all the elements in a flatter manner.

Current op:

[
  "obj",
  "level1.level2.level3.key",
  [
    "arrayObj.one[0].name",
    "arrayObj.one[0].point"
  ]
]

Expected:

[
  "obj",
  "level1.level2.level3.key",
  "arrayObj.one[0].name",
  "arrayObj.one[0].point"
]

Below I have attached the snippet I tried.

const allPaths = (obj, path = "") =>
  Object.keys(obj).reduce((res, el) => {
    if (Array.isArray(obj[el]) && obj[el].length) {
      return [...res, ...obj[el].map((item, index) => {
        return [...res, ...allPaths(item, `${path}${el}[${index}].`)];
      })];
    } else if (typeof obj[el] === "object" && obj[el] !== null) {
      return [...res, ...allPaths(obj[el], `${path}${el}.`)];
    }
    return [...res, path + el];
  }, []);

const obj = {
  obj: 'sample',
  level1: {
    level2: {
      level3: {
        key: 'value'
      }
    }
  },
  arrayObj: {
    one: [{
        name: 'name',
        point: 'point'
      },
      {
        name: 'name2',
        point: 'point2'
      },
      {
        name: 'name2',
        point: 'point2'
      }
    ]
  }
}

console.log(allPaths(obj));
React Noob
  • 91
  • 1
  • 4
  • 1
    `console.log(allPaths(obj).flat());` ? – 0stone0 Oct 20 '21 at 15:16
  • Does this answer your question? [Javascript reflection: Get nested objects path](https://stackoverflow.com/questions/32141291/javascript-reflection-get-nested-objects-path) – 0stone0 Oct 20 '21 at 15:18

1 Answers1

1

UPDATE: I didn't understood the question previously correctly. Now i do. So yes the below code will solve the problem for you.

You want your object to be flattened with dots

If thats the case the below should work

const obj = {
  obj: 'sample',
  level1: {
    level2: {
      level3: {
        key: 'value'
      }
    }
  },
  arrayObj: {
    one: [{
        name: 'name',
        point: 'point'
      },
      {
        name: 'name2',
        point: 'point2'
      },
      {
        name: 'name2',
        point: 'point2'
      }
    ]
  }
}

function flatten(data, prefix) {
  let result = {}
  for(let d in data) {
    if(typeof data[d] == 'object') Object.assign(result, flatten(data[d], prefix + '.' + d))
    else result[(prefix + '.' + d).replace(/^\./, '')] = data[d]
  }
  return result
}

console.log(flatten(obj, ''))
Achyut
  • 768
  • 3
  • 11
  • 28