1

I have a json object, which needs to be iterated, I can make use of iteration as a function but wanted to see if there is a simpler way to do so. Object is as shown below:

obj = [
  {
    name: 'FolderA',
    child: [
      {
        name: 'FolderB',
        child: [
           {
            name: 'FolderC0',
            child: [],
          },
          {
            name: 'FolderC1',
            child: [],
          }
         ]
       }
   ],
 },
 {
    name: 'FolderM'
    child: []
 }
]

On some event I get level, like

level = "0-0-1"

Which I split to get [0, 0, 1] Meaning, 0th index, nested 0th index and further nested 1st index, which I get like:

obj[0][0][1], 

But since nested structure depth is unknown I want the above to be generated dynamically, something like this:

obj + [0] + .children[0] + .children[1], 

Not sure if this can be done, but if there is, please let me know, else I will have to use recursive function. Thanks

2
  • You should use recursion for iteration nested objects. Commented Dec 13, 2018 at 11:35
  • Side note: JSON is a string representation of an object. What you have is the object itself, not its string representation. So please just say "object" instead of "json object"; and don't tag it with json. Commented Dec 13, 2018 at 11:46

1 Answer 1

1

You can split the string and then use reduce on the array of indexes:

const arr = [
  {
    name: 'FolderA',
    child: [
      {
        name: 'FolderB',
        child: [
          {
            name: 'FolderC0',
            child: [],
          },
          {
            name: 'FolderC1',
            child: [],
          },
        ],
      },
    ],
  },
  {
    name: 'FolderM',
    child: [],
  },
];
const getObject = (arr, path) =>
  path
    .split('-')
    .reduce((result, key) => result.child[key], {
      child: arr,
    });

console.log(getObject(arr, '0-0-1'));

Sign up to request clarification or add additional context in comments.

3 Comments

Charm!! Thanks.
Can you give me link of a resource to learn advance javascript?
@MichaelPhilips The documentation here is useful when working with array (reduce is in there as well). A good read is the YDKJS series but this one will get you familiar with ES6 syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.