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.
   }
  }
 }
fereshen
  • 3
  • 1
  • 2
  • _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. – Boaz May 02 '21 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](https://stackoverflow.com/questions/15690706/recursively-looping-through-an-object-to-build-a-property-list/53620876#53620876) for relevant techniques. – Boaz May 02 '21 at 18:09
  • `console.log(JSON.stringify(obj0))` – mplungjan May 02 '21 at 18:12

2 Answers2

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

mplungjan
  • 169,008
  • 28
  • 173
  • 236