0

how can i log array values from all arrays in nested objects in obj0? Assuming i do not have info about how many nested objects i have.

const obj0 = {
  array0: [1,2,3],
  obj1: {
    array1: [5,6,7],
    obj2: {
      array2: [8,9,10],
     //obj3 etc.
   }
  }
 }
3
  • Assuming i do not have info about how many nested objects i have - do you mean when the depth of the nested objects is unknown? If that's the case, you will probably need to set some limit, or this process will run for a very long time. Commented May 2, 2021 at 18:06
  • The main challenge seems to be the iteration over the object properties. See Recursively looping through an object to build a property list for relevant techniques. Commented May 2, 2021 at 18:09
  • console.log(JSON.stringify(obj0)) Commented May 2, 2021 at 18:12

2 Answers 2

1

you probably can use something like this here

I just created a simple function that recursively call the object and only logs the array elements.

const obj0 = {
  array0: [1, 2, 3],
  obj1: {
    array1: [5, 6, 7],
    obj2: {
      array2: [8, 9, 10],
    },
  },
};

const a = function (obj) {
  Object.entries(obj).map((e, i) => {
    i === 0 && e[1].map((e) => console.log(e));
    i === 1 && a(e[1]);
  });
};

a(obj0);

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

Comments

0

Would this be useful?

const obj0 = {
  array0: [1,2,3],
  obj1: {
    array1: [5,6,7],
    obj2: {
      array2: [8,9,10],
     //obj3 etc.
   }
  }
 }

const str = JSON.stringify(obj0)
const arrs = [...str.matchAll(/\[(.*?)\]/g)].map(arr => arr[1])
console.log(arrs)

Wrap in [] if you want arrays back: => [arr[1]]

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.