Search code examples
javascriptlodash

a better way if iterating an object using lodash


Using lodash I'm wondering if there is a better way of doing this.

I've got an array object like below.

    {
        "ALFA ROMEO": {
            "MITO": [{
                "carData": "stuff"
            }]
        },
        "AUDI": {
            "A1": [{
                    "carData": "stuff"
                },
                {
                    "carData": "stuff"
                }
            ],
            "Q3": [{
                "carData": "stuff"
            }],
            "A3": [{
                    "carData": "stuff"
                },
                {
                    "carData": "stuff"
                },
                {
                    "carData": "stuff"
                }
            ]
        }
    }

I'm using _.forEach to iterate through the object to structure the output simular to this:

    ALFA ROMEO - 1
        MITO (1)
    AUDI - 5
        A1 (2)
        Q3 (1)
        A3 (2)

Using this I can get part way there:

        _.forEach(jData, (val, key) => {
            console.log(key)
            _.forEach(val, (val, key) => {
                console.log('    ' + key + ' (' + val.length + ')')
            })
        })

Which give me this:

    ALFA ROMEO
        MITO (1)
    AUDI
        A1 (2)
        Q3 (1)
        A3 (2)

My question is this:

a) Is there a better way of doing this without a double loop?

b) Is the only way to get a total for each make by totalling up the model counts, or is there a better way of doing this?

Thanks.


Solution

  • There's no way to do it without nested looping, since you need to print each model.

    You can use _.sumBy() to get the total lengths of the models, so you can show that before the loop.

    const jData = {
      "ALFA ROMEO": {
        "MITO": [{
          "carData": "stuff"
        }]
      },
      "AUDI": {
        "A1": [{
            "carData": "stuff"
          },
          {
            "carData": "stuff"
          }
        ],
        "Q3": [{
          "carData": "stuff"
        }],
        "A3": [{
            "carData": "stuff"
          },
          {
            "carData": "stuff"
          },
          {
            "carData": "stuff"
          }
        ]
      }
    };
    
    _.forEach(jData, (val, key) => {
      let total = _.sumBy(_.toArray(val), 'length');
      console.log(`${key} - ${total}`)
      _.forEach(val, (val, key) => {
        console.log(`${key} (${val.length})`)
      })
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>