最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

ecmascript 6 - Length of Array of Objects in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Dec 15, 2018 at 5:40 Null isTrue asked Dec 15, 2018 at 5:22 Null isTrueNull isTrue 1,9168 gold badges30 silver badges50 bronze badges 3
  • 5 users.reduce((acc, o) => acc + Object.keys(o).length, 0) – Andrew Li Commented Dec 15, 2018 at 5:24
  • 1 Object.keys(users[1]).length – Deepika Rao Commented Dec 15, 2018 at 5:27
  • 1 @DeepikaRao that only gives the length for [1] which is 3 – Null isTrue Commented Dec 15, 2018 at 5:32
Add a ment  | 

1 Answer 1

Reset to default 10

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

发布评论

评论列表(0)

  1. 暂无评论