简体   繁体   中英

Find a value in an array of populated objects mongdb - lodash

Maybe this question is duplicate or asked several times in different ways but still haven't solved my problem. I am creating nodejs api returning 10,000 populated objects from mongodb. I want to filter array based on the object.

{color: red}

How can i use lodash filter to return array with containing specified filter object.

[
  {
    "value": 200,
    "newEle": {
      "gradient": "true",
      "mode": {
        "color": "red"
      }
    }
  },
  {
    "value": 100,
    "newEle": {
      "gradient": "false",
      "mode": {
        "color": "blue"
      }
    }
  }
]

If you are specifically trying to filter by just the color you can use vanilla JS's .filter() to get all the objects with the color property of red into a new array:

 const arr = [ { "value": 200, "newEle": { "gradient": "true", "mode": { "color": "red" } } }, { "value": 100, "newEle": { "gradient": "false", "mode": { "color": "blue" } } } ], color = "red", res = arr.filter(obj => obj.newEle.mode.color === color); console.log(res); 

If you wish to use lodash specifically you can use _.filter() :

 const arr = [ { "value": 200, "newEle": { "gradient": "true", "mode": { "color": "red" } } }, { "value": 100, "newEle": { "gradient": "false", "mode": { "color": "blue" } } } ], color = "red", res = _.filter(arr, obj => obj.newEle.mode.color === color); console.log(res); 
 <script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script> 

When using lodash, it's as simple as this.

 let filtered_array = _.filter(myArr, { color: 'red' });

However, since you have nested nested objects, you'd want to create a predicate that accesses the nested value. You do this with an array.

 let filtered_array = _.filter(myArr, ['newEle.mode.color', 'red']);

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