Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
How to get total length of all items in object with arrays

I want to get the total of all items in object with array. for example

const obj = {
  one: [1, 4],
  two: [4, 6]
}

I should get total of 4.

I tried

const obj = {
  one: [1, 4],
  two: [4, 6]
}

let total = 0;
const objKeys = Object.keys(obj);

for (let index = 0; index < objKeys.length; index++) {
  total += obj[objKeys[index]].length
}

console.log(total);

Is there a simpler way of doing this?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You could grab the values of your object, which would be an array of arrays of the following shape:

[[1, 4], [4, 6]]

and then flatten this array with .flat() which gives:

[1, 4, 4, 6];

And then grab the .length of that array.

See example below:

const obj = {one: [1, 4],two: [4, 6]}; 

const res = Object.values(obj).flat().length;
console.log(res);

Note, that if your goal is for efficiency, you can use a standard for...in loop to loop the keys of your object, and then add to a total like as shown below. This also avoids the overhead of creating additional arrays to store the keys/values:

const obj = {one: [1, 4], two: [4, 6]};
let total = 0;
for(const key in obj) 
  total += obj[key].length;
console.log(total);

about 4 years ago · Juan Pablo Isaza Report

0

reduce() on Object.values(obj) would be a great fit:

const obj = {
  one: [1, 4],
  two: [4, 6]
}

let total = Object.values(obj).reduce((prev, cur) => prev + cur.length, 0);

console.log(total); // 4

about 4 years ago · Juan Pablo Isaza Report

0

const obj = {
  one: [1, 4],
  two: [4, 6]
}

let total = 0;

Object.keys(obj).forEach(element => { total += obj[element].length  } )

console.log(total);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!