Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 899
Null isTrue Avatar asked Dec 15 '18 05:12

Null isTrue


People also ask

How do you find the length of an array of objects?

You can simply use the Object. keys() method along with the length property to get the length of a JavaScript object. The Object. keys() method returns an array of a given object's own enumerable property names, and the length property returns the number of elements in that array.

How do you find the length of an array in JavaScript?

The JavaScript array length property states the number of items in an array. To find the length of an array, reference the object array_name. length. The length property returns an integer.

How do you find the length of an array of objects in TypeScript?

To get the length of an object in TypeScript:Use the Object. keys() method to get an array of the object's keys. Access the length property on the array of keys. The length property will return the number of key-value pairs in the object.

What is the length of an object JavaScript?

Method 1: Using the Object. keys() method is used to return the object property name as an array. The length property is used to get the number of keys present in the object. It gives the length of the object.


1 Answers

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);
like image 62
CertainPerformance Avatar answered Oct 19 '22 16:10

CertainPerformance