Count of arrays inside an object!

Asked

Viewed 99 times

1

I have an object with arrays inside, inside that array.. there are other objects! how can I know the total length of all arrays inside the first object! ex:

    let items = { 
        0: [
            { foo: 'foo' },
            { bar: 'bar' },
        ], // length = 2 
        1: [
            { foo: 'foo' },
        ], // length = 1 
    }
    
    let total = 0;
    total += items[0].length;
    total += items[1].length;
    
    console.log(total);

Is there any less verbose way to run this excerpt ? example if I have 50~100 items it is impossible to keep this code

1 answer

4


You just need to use a loop that goes through all the properties that exist in the object, and add the associated arrays sizes.

Thus:

let items = { 
    0: [
        { foo: 'foo' },
        { bar: 'bar' },
    ], // length = 2 
    1: [
        { foo: 'foo' },
    ], // length = 1 
}

let total = 0;
for (let prop of Object.keys(items)){ //percorrer todas as propriedades
  total += items[prop].length; //somar o tamanho do array na propriedade corrente
}
    
console.log(total);

I used the function keys of Object that returns an array with all object properties.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.