'A function to obtain all leaf node properties of an object in an array of string in javascript

Request you to please help in building a function in javascript to obtain the mentioned output from the input given.

INPUT : An object (possibly a nested object)

example :

{

"message":"string" ,

"data1": {

    "Output1": {

        "leaf1": "abc",

        "Leaf2": "123"

    }

}

"data2": {

    "Output2": {

        "leaf3": "abc",

        "leaf4": "123"

    }

}  

}

OUTPUT : An array of string

Example : str= ["message", "data1.Output1.leaf1", "data1.Output1.leaf2" , "data2.Output2.leaf3","data2.Output2.leaf4"]



Solution 1:[1]

Something like this it will work

const getBranches = (data, prefix=[]) => {
  if (typeof(data) !== 'object') {
    return prefix.join('.')
  }
  return Object.entries(data).flatMap(([k, v]) => getBranches(v, [...prefix, k]))

  }

  const data = {
    "message": "string",
    "data1": {
      "Output1": {
        "leaf1": "abc",
        "Leaf2": "123"
      }
    },
    "data2": {
      "Output2": {
        "leaf3": "abc",
        "leaf4": "123"
      }
    }
  }


console.log(getBranches(data))

Second version

const data = {
  "message": "string",
  "data1": {
    "Output1": {
      "leaf1": [{
        "b": {
          "c": "12"
        }
      }]
    }
  },
  "data2": {
    "Output2": {
      "leaf3": "abc",
      "leaf4": "123"
    }
  }
}
const getBranches = (data, prefix = []) => {
  if (typeof(data) !== 'object') {
    return prefix.join('.')
  }
  return Object.entries(data).flatMap(([k, v]) => Array.isArray(data) ? getBranches(v, [...prefix]) : getBranches(v, [...prefix, k]))
}

console.log(getBranches(data))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1