Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring nested for each loop

I have below code to iterated the stickers info from object. For that I am using two nested for each. Is there any better method in lodash to refactor below code without using nested forEach or any better suggestion.

var stickers = [];
_.forEach(data.families.categories, function (category) {
    _.forEach(category.stickers, function (sticker) {
        stickers.push(sticker);
    });
});

Below is the object sample

var data = {
  "families": {
    "id": "my_family",
    "categories": [
      {
        "label": "sample-1",
        "id": "family-0",
        "stickers": [
          "aa",
          "bb",
          "cc"
        ]
      },
      {
        "label": "US",
        "id": "family-1",
        "stickers": [
          "DD",
          "EE"
        ]
      },
      {
        "label": "sample-2",
        "id": "family-2",
        "stickers": [

        ]
      },
      {
        "label": "sample-3",
        "id": "family-3",
        "stickers": [
          "FF",
          "GG",
          "HH",
          "II",
          "JJ"
        ]
      }
    ]
  }
}
like image 244
Rakesh Kumar Avatar asked Oct 29 '25 08:10

Rakesh Kumar


1 Answers

Lodash provides the flatMap function which will do what you want:

var stickers =_.flatMap(data.families.categories, 'stickers');

	var data = {
  "families": {
    "id": "my_family",
    "categories": [
      {
        "label": "sample-1",
        "id": "family-0",
        "stickers": [
          "aa",
          "bb",
          "cc"
        ]
      },
      {
        "label": "US",
        "id": "family-1",
        "stickers": [
          "DD",
          "EE"
        ]
      },
      {
        "label": "sample-2",
        "id": "family-2",
        "stickers": [

        ]
      },
      {
        "label": "sample-3",
        "id": "family-3",
        "stickers": [
          "FF",
          "GG",
          "HH",
          "II",
          "JJ"
        ]
      }
    ]
  }
}
    
    var stickers =_.flatMap( data.families.categories, 'stickers');

document.getElementById('result').textContent = JSON.stringify(stickers);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

<p>
  <pre id="result"></pre>
</p>
like image 176
Gruff Bunny Avatar answered Oct 30 '25 23:10

Gruff Bunny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!