-3

How to write the best javascript function for getting this output. ['1','p1','p11','2','p2','p21'] for this input.

const arr = [{

        "children": [{
            "property1": "1",

            "children": [{
                "property1": "p1",

                "children": [{
                    "property1": "p11",

                    "children": [

                    ]
                }]
            }]
        }]
    },
    {

        "children": [{
            "property1": "2",

            "children": [{
                "property1": "p2",

                "children": [{
                    "property1": "p21",

                    "children": [

                    ]
                }]
            }]
        }]
    }
]

How to get the output using recursive function. It is loop of children. if the children length is 0 then don't add otherwise add arrays of property1.

ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
Trinu
  • 1,721
  • 3
  • 21
  • 41
  • Please post a [mcve] of your attempt, as an [edit] to your question, and say specifically where you're stuck. – Luca Kiebel Sep 26 '18 at 18:59
  • 2
    Yes, using a recursive function with a loop of the children sounds like a good solution. Use that approach! If you need help with your implementation, please show us your attempt. – Bergi Sep 26 '18 at 19:00
  • See [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Sep 26 '18 at 22:05

1 Answers1

2

You can write a simple recursive function for this.

  • First check whether the current Array element or child contains property1 or not. if it is present simply push property1 to the result array.

  • Then you need to check whether the child has its own child(or subchilds) if it has its own children than recursively call the getProperty() method passing the child array as the new parameter to the function along with the result array.

const arr = [{ "children": [{ "property1": "1", "children": [{ "property1": "p1", "children": [{ "property1": "p11", "children": [ ] }] }] }] }, { "children": [{ "property1": "2", "children": [{ "property1": "p2", "children": [{ "property1": "p21", "children": [ ] }] }] }] } ];

function getProperty(arr, result){
  for(var i = 0; i < arr.length; i++){
    if(arr[i].property1)
      result.push(arr[i].property1);
    if(arr[i].children && arr[i].children.length)
      getProperty(arr[i].children, result);
  }
}
let result = [];
getProperty(arr,result)
console.log(result);
amrender singh
  • 7,949
  • 3
  • 22
  • 28