Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda