简体   繁体   中英

Lodash multiple key with multiple array of values filter

I'm trying to filtering multidimensional object using lodash filter object . Below are my sample object to filter data.

    {
  "0": {
    "details": {
      "rating": 2.5,
      "amenities": {
        "airConditioning": true,
      },
    },
    "rates": {
      "packages": [
        {
          "refundable": "Yes",
        }
      ]
    }
  },
  {
  "1": {
    "details": {
      "rating": 3,
      "amenities": {
        "airConditioning": false,
      },
    },
    "rates": {
      "packages": [
        {
          "refundable": "Yes",
        }
      ]
    }
  },
  {
  "2": {
    "details": {
      "rating": 2,
      "amenities": {
        "airConditioning": true,
      },
    },
    "rates": {
      "packages": [
        {
          "refundable": "No",
        }
      ]
    }
  },
}

I have tried

    console.log(_.filter( data, { 'details.rating': '2', 'details.rating': '3' } ));

_.filter(data, function (item) {
  return ['2', '3'].indexOf(item.details.rating) >= 0
})

And followed this too Filtering multiple value with multiple key in json array using lodash

nothing working

Your JSON has extra { before the key "1" and "2" . So remove that and it will work.

  var data = { "0": { "details": { "rating": 2.5, "amenities": { "airConditioning": true, }, }, "rates": { "packages": [ { "refundable": "Yes", } ] } }, "1": { "details": { "rating": 3, "amenities": { "airConditioning": false, }, }, "rates": { "packages": [ { "refundable": "Yes", } ] } }, "2": { "details": { "rating": 2, "amenities": { "airConditioning": true, }, }, "rates": { "packages": [ { "refundable": "No", } ] } } }; var result = _.filter(data, (item) => { return [2, 3].indexOf(item.details.rating) >= 0 }); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

Notice the array elements inside the filter [2, 3] . They are integer type as item.details.rating is an integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM