0

I have array of objects like this:

data = [
 {
   "name":"abc",
   "email":"abc@gmail.com"
 },
 {
   "name": "bcd",
   "email": "bcd@gmail.com",
   "info":[
     {
        "email": "bcd@gmail.com",
        "count":5
     }
     ]
 },
 {
    "name": "hfv",
    "email": "hfv@gmail.com",
    "info":[
      {
      "email": "hfv@gmail.com",
      "count":5
      },
      {
        "email": "hfv@gmail.com",
        "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": "bcd@gmail.com",
   "info":[
     {
        "email": "bcd@gmail.com",
        "count":5
     }
     ]
 },
 {
    "name": "hfv",
    "email": "hfv@gmail.com",
    "info":[
      {
      "email": "hfv@gmail.com",
      "count":5
      },
      {
        "email": "hfv@gmail.com",
        "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?

mahan
  • 9
  • 2
  • Does this answer your question? [Filter array of object with conditional statement](https://stackoverflow.com/questions/67590053/filter-array-of-object-with-conditional-statement) – pilchard Mar 10 '22 at 10:23

1 Answers1

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.

LéoValette
  • 106
  • 2
  • 1
    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. – Alex Ander Mar 10 '22 at 10:02
  • You can slightly improve solution: `data.filter(obj => obj.info?.some(({ count }) => count > 1))` – A1exandr Belan Mar 10 '22 at 18:46