0

I have array of objects like this:

data = [
 {
   "name":"abc",
   "email":"[email protected]"
 },
 {
   "name": "bcd",
   "email": "[email protected]",
   "info":[
     {
        "email": "[email protected]",
        "count":5
     }
     ]
 },
 {
    "name": "hfv",
    "email": "[email protected]",
    "info":[
      {
      "email": "[email protected]",
      "count":5
      },
      {
        "email": "[email protected]",
        "count":7
        }
      ]
  }
]

I want to to change data in such a way that only objects that have count>1 should exist

so the output should like this:

[{
   "name": "bcd",
   "email": "[email protected]",
   "info":[
     {
        "email": "[email protected]",
        "count":5
     }
     ]
 },
 {
    "name": "hfv",
    "email": "[email protected]",
    "info":[
      {
      "email": "[email protected]",
      "count":5
      },
      {
        "email": "[email protected]",
        "count":7
        }
      ]
  }
]

the data array should look like this, how I can I loop through this array of objects and remove objects that have count<=1?

1

1 Answer 1

0

You can use array.filter() to achieve it

const result = data.filter(obj => obj.info && obj.info.filter(info => info.count > 1).length > 0)

You may need to filter info objects as well... depends of your need. But you have everything you need here.

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

2 Comments

Good answer here, but could be slightly wrong. The wording of the question is slightly unclear, does the OP want ALL parent objects, but only show there items if the item count if greater than one, or does the OP want to filter out the parent objects too? If it's the first, then the first filter should be replaced with a map instead.
You can slightly improve solution: data.filter(obj => obj.info?.some(({ count }) => count > 1))

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.