Home > OS >  How to get total length of all items in object with arrays
How to get total length of all items in object with arrays

Time:04-29

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

let total = 0;

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

console.log(sum);

  • Related