Delete object with certain key value from filtering array of objects

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Delete object with certain key value from filtering array of objects on this date .

I have an array of objects and I filtering it:

const test = [
  {
    "id":2,
    "category_id":1,
    "features":["blah","blah","blah","blah"],
    "options":
    {
      "option1":
        {
          "b":22,"c":105,"d":70,"e":345
        },
      "option2":
        {
          "c":25,"c":41,"d":70,"e":345
        }
    }
  },
  {
    "id":4,
    "category_id":2,
    "features":["blah","blah","blah","blah"],
    "options":
    {
      "option1":
        {
          "b":22,"c":105,"d":70,"e":345
        },
      "option2":
        {
          "c":25,"c":41,"d":70,"e":345
        }
    }
  },
  {
    "id":7,
    "category_id":4,
    "features":null,
    "options":null
  },
  {
    "id":11,
    "category_id":6,
    "features":["blah","blah","blah","blah"],
    "options":
    {
      "option1":
        {
          "b":22,"c":105,"d":70,"e":345
        },
      "option2":
        {
          "c":25,"c":41,"d":70,"e":345
        }
    }
  }
]


const filtered = test.filter((t) => {


})

Objects with “category_id: 4” don’t have “options” but inside the filter I need all options value that exist:

const filtered = test.filter((t) => {
  const tOptions = Object.values(t.options)

})

it gives me an error because some options does’t exist. I know how to modify an array and delete objects without options (with Lodash)

_.reject(test, function(el) { return el.category_id === 4 })

but I can’t modify “test” array because of the logic that goes after. Somehow I need this result without touching an array itself:

[
 Object 
 {
  b:22,
  c:105,
  d:70,
  e:345
 }, 
Object 
 {
  c:41,
  d: 70,
  e: 345
 }
]

I really give up. Please help.

Answer

Add an if condition to check if t.options is not null

const filtered = test.filter((t) => {
  if(t.options) { // null and undefined are falsey
     const tOptions = Object.values(t.options);

  } else {
      return false;
  }
});
``