raklos
raklos

Reputation: 28545

find object in nested array with lodash

I have json data similar to this:

    {

  "Sections": [
    {
      "Categories": [
        {
          "Name": "Book",
          "Id": 1,
          "Options": [
            {
              "Name": "AAAA",
              "OptionId": 111
            },
            "Selected": 0
        },
        {
          "Name": "Car",
          "Id": 2,
          "Options": [
            {
              "Name": "BBB",
              "OptionId": 222
            },
            "Selected": 0
        },


      ],
      "SectionName": "Main"
    },
    ... more sections like the one above

  ]
}

Given this data, I want to find a category inside a section based on its (Category) Id, and set its selected option, I tried this, but couldn't get it to work....Note Category Id will be unique in the whole data set.

_.find(model.Sections, { Categories: [ { Id: catId } ]});

Upvotes: 1

Views: 4286

Answers (1)

acontell
acontell

Reputation: 6922

According to your data model, it looks like you're trying to find an element that is inside a matrix: Sections can have multiple Categories and a Category can have multiple types (car, book...).

I'm afraid there isn't a function in lodash that allows a deep find, you'll have to implement it the 'traditional' way (a couple of fors).

I provide this solution that is a bit more 'functional flavoured' than the traditional nested fors. It also takes advantage of the fact that when you explicitly return false inside a forEach, the loop finishes. Thus, once an element with the provided id is found, the loop is ended and the element returned (if it's not found, undefined is returned instead).

Hope it helps.

const findCategoryById = (sections, id) => {
  var category;
  _.forEach(sections, (section) => {
    category = _.find(section.Categories, ['Id', id]);
    return _.isUndefined(category);
  });
  return category;
};


const ex = {
  "Sections": [{
    "Categories": [{
        "Name": "Book",
        "Id": 1,
        "Options": [{
          "Name": "AAAA",
          "OptionId": 111
        }],
        "Selected": 0
      },
      {
        "Name": "Car",
        "Id": 2,
        "Options": [{
          "Name": "BBB",
          "OptionId": 222
        }],
        "Selected": 0
      }
    ],
    "SectionName": "Main"
  }]
};

console.log(findCategoryById(ex.Sections, 2));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

Upvotes: 4

Related Questions