ES6 Filter array of object were a property exists

10,197

Solution 1

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)
    

Solution 2

Use Boolean wrapper, it's more clear:

const filteredItems = items.filter(item => Boolean(item.title))
Share:
10,197

Related videos on Youtube

DoblyTufnell
Author by

DoblyTufnell

Updated on June 04, 2022

Comments

  • DoblyTufnell
    DoblyTufnell almost 2 years

    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

  • Ilija Iličić
    Ilija Iličić over 2 years
    What does !! mean in JS?
  • Fatih Turgut
    Fatih Turgut over 2 years