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?
>Solution :
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);