Skip to content
Advertisement

Length of Array of Objects in JavaScript

I understand that finding the length of a JS object has been answered extensively here

With one of the suggested solutions being Object.keys(myObj).length

However, I’m struggling to find out how can I find the length of all properties contained on an array of objects.

ie:

const users = [
  {
    firstName: "Bruce",
    lastName: "Wayne",
    id: "1",
  },

  {
    firstName: "Peter",
    lastName: "Parker",
    id: "2"
  },

  {
    firstName: "Tony",
    lastName: "Stark",
    id: "3"
  }
];

Object.keys(users).length //3

Given the example above, How can I output a length of 9 retrieving all the properties on the array of objects?

Could this be done using a reduce method? Thanks in advance.

Advertisement

Answer

Yes, reduce is the appropriate method – on each iteration, add the number of keys of the current object to the accumulator to sum up the keys of every item:

  const users = [
  {
    firstName: "Bruce",
    lastName: "Wayne",
    id: "1",
  },

  {
    firstName: "Peter",
    lastName: "Parker",
    id: "2"
  },

  {
    firstName: "Tony",
    lastName: "Stark",
    id: "3"
  }
];

const totalProps = users.reduce((a, obj) => a + Object.keys(obj).length, 0);
console.log(totalProps);
Advertisement