3

I am trying to filter an array of objects to return just the objects that have property the other objects do not have. Not a value in a property, but the property itself.

results [
   { 
      "title": "Foo",
      "value":  34
   },
   {
       "value": 43
   },
   {
       "title": "The Title",
       "value": 99
]

In the example above I want the first and last object as they have a 'title' property, in an new array of objects.

I looked at 'filter' but it seems to work with values.. How do I this?

Thanks

DoblyTufnell
  • 75
  • 1
  • 2
  • 5

2 Answers2

7

You can filter items like following code, it filters if title property exists.

    const items = [
       { 
          "title": "Foo",
          "value":  34
       },
       {
           "value": 43
       },
       {
           "title": "The Title",
           "value": 99
       }
    ];
    

    const filteredItems = items.filter(item => !!item.title)
    
Fatih Turgut
  • 319
  • 3
  • 9
4

Use Boolean wrapper, it's more clear:

const filteredItems = items.filter(item => Boolean(item.title))
kli
  • 456
  • 3
  • 12