Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
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"]

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!