0

I wanted to know what is the best way to extract the same named object from a multi level nested object.

I currently have an object that looks like this, and i want to extract out the parentLocationCluster objects out of it.

 const foo = {
  id: '1',
  name: 'boo',
  parentLocationCluster: {
    id: 1,
    name: 'foo',
    parentLocationCluster: {
      id: 2,
      name: 'fii',
      parentLocationCLuster: {
        id: 3,
        name: 'faa',
      },
    },
  },
};

Now I could just a nested if statement like so:

const { parentLocationCluster } = foo;
if(parentLocationCluster) {
//do something
if(parentLocationCluster.parentLocationCluster) {
  //do something
 }
}

but i feel this is significantly inefficient ( which is what i am doing at the moment). Also, the objects could vary with the number of nested parentLocationCluster objects i.e. an object could contain 10 levels of parentLocationClusters.

What would be the best way to do this?

4
  • 1
    Do you need the value of the "deepest" parentLocationCluster? Do you want to know if there are x levels of parentLocationClusters? Do you...? - Please be more specific on the actual use case. Commented Jun 15, 2019 at 11:23
  • Do you want to do something with each of them? Commented Jun 15, 2019 at 11:28
  • 1
    @andreas "I wanted to know what is the best way to extract the same named object from a multi level nested object." Commented Jun 15, 2019 at 11:33
  • @andreas i need the value of ALL names from each parentLocationCluster Commented Jun 15, 2019 at 15:38

1 Answer 1

1

The following snippet recursively accesses all nested clusters to any depth and does something with them.

const foo = {
  id: '1',
  name: 'boo',
  parentLocationCluster: {
    id: 1,
    name: 'foo',
    parentLocationCluster: {
      id: 2,
      name: 'fii',
      parentLocationCluster: {
        id: 3,
        name: 'faa',
      },
    },
  },
};

function readCluster(obj) {
  const cluster = obj.parentLocationCluster
  if (cluster) {
    // Do something
    console.log(cluster.name)
    readCluster(cluster)
  } else
    return;
}

readCluster(foo);

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

Comments

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.