1

Consider below example. I am using Lodash

"home":[
   {
      "data":{
         "interests":["sports", "travel", "boxing"],
         "city":["x", "y", "z"],
         "name":"test1"
      },
      "count":["1", "2"],
      "country":"CA"
   },
   {
      "data":{
         "interests":["painting", "travel", "dancing"],
         "city":["a", "y", "b"],
         "name":"test2"
      },
      "count":["1","3"],
      "country":"US"
   }
]

If I'll try the function on key value pair example :

_.find(home, ['data.country', 'US']);  // It is returning me the 2nd object

requirement :

I want all the objects where data.interests is 'dancing'.

Tried :

_.find(home, ['data.interests', 'dancing'])  // It is returning [] 

I have also tried filter(), where() and map but unable to get the complete object.

Thanks in advance.

1 Answer 1

1

You can use vanilla JS or lodash funcntions - Filter the array, and for each item check if the data.interests array includes the requested word.

Vanilla:

const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]

const result = home.filter(o => o.data.interests.includes('dancing'))

console.log(result)

Lodash:

const home = [{"data":{"interests":["sports","travel","boxing"],"city":["x","y","z"],"name":"test1"},"count":["1","2"],"country":"CA"},{"data":{"interests":["painting","travel","dancing"],"city":["a","y","b"],"name":"test2"},"count":["1","3"],"country":"US"}]

const result = _.filter(home, o => _.includes(o.data.interests, 'dancing'))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.