How to get any arrays and nothing else from an object?

If I have an object that looks like the following:

{
  a: "String",
  b: [1, 2, 3],
  c: ["a", "b", "c"]
}

…meaning it contains one or more arrays and sometimes some other stuff like strings as well. With Object.values(myObject) I can get the values, but what would be the best way to get all the arrays - but not the other stuff, if there is any - inside of an object? I should clarify: I don’t know the property names beforehand, if that makes any difference.

You can loop through an objects properties and then just check if they are an array…

I hope that helps. :slight_smile:

You can do it like so:

const obj = {
  a: "String",
  b: [1, 2, 3],
  c: ["a", "b", "c"],
  d: 1,
  e: () => {},
  f: {a: 1},
  g: null,
  h: []
};

const filtered = Object.entries(obj)
  .map(([key, value]) => Array.isArray(value) ? value : null)
  .filter(Boolean);

console.log(filtered);

// Array(3) [ (3) […], (3) […], [] ]
​// 0: Array(3) [ 1, 2, 3 ]
​// 1: Array(3) [ "a", "b", "c" ]
​// 2: Array []

This uses Object.entries to convert the object to an array, then Array.map to create a new array containing either the value if it is an array or null. Finally, the filter(Boolean) removes all of the null values you don’t care about.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.