Carol.Kar
Carol.Kar

Reputation: 5345

Filter away obj in array with null values

I would like to filter away the objects in my array of objects that has null or "" values.

let data = [{
  "name": "Product 2",
  "link": "/stock/product2",
  "category": "234",
  "description": ""
}, {
  "name": "Product 1",
  "link": "/stock/product1",
  "category": "1231",
  "description": ""
}, {
  "name": "",
  "link": null,
  "ticker": "",
  "description": ""
}]

data = data.filter(cv => (cv.name === "" && cv.link === null));

console.log(JSON.stringify(data))

As you can see above I currently get the false object back. I would like to get back:

{
  "name": "Product 2",
  "link": "/stock/product2",
  "category": "234",
  "description": ""
}, {
  "name": "Product 1",
  "link": "/stock/product1",
  "category": "1231",
  "description": ""
}

Any suggestions what I am doing wrong?

Upvotes: 1

Views: 140

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386519

You could get the values of the objects and check if some value is truty, then keep this object, otherwise filter it out.

let data = [{ name: "Product 2", link: "/stock/product2", category: "234", description: "" }, { name: "Product 1", link: "/stock/product1", category: "1231", description: "" }, { name: "", link: null, ticker: "", description: "" }]

data = data.filter(o => Object.values(o).some(Boolean));

console.log(data);

Upvotes: 1

Ahmad Noor
Ahmad Noor

Reputation: 149

The best solution for this is

let data = [{
    "name": "Product 2",
    "link": "/stock/product2",
    "category": "234",
    "description": ""
  },
  {
    "name": "Product 1",
    "link": "/stock/product1",
    "category": "1231",
    "description": ""
  }, {
    "name": "",
    "link": null,
    "ticker": "",
    "description": ""
  }
]
data = data.filter(cv => (cv.name && cv.link));
console.log(data);

Upvotes: 1

Djaouad
Djaouad

Reputation: 22766

Because filter doesn't work as you think, it keeps elements that meet the condition, so invert your condition and it should work as expected:

let data = [{
  "name": "Product 2",
  "link": "/stock/product2",
  "category": "234",
  "description": ""
}, {
  "name": "Product 1",
  "link": "/stock/product1",
  "category": "1231",
  "description": ""
}, {
  "name": "",
  "link": null,
  "ticker": "",
  "description": ""
}]

data = data.filter(cv => !(cv.name === "" || cv.link === null));

console.log(JSON.stringify(data))

Upvotes: 5

Michał
Michał

Reputation: 905

This will filter out items which have at least one field with null or "" value.

let data = [{
  "name": "Product 2",
  "link": "/stock/product2",
  "category": "234",
  "description": ""
}, {
  "name": "Product 1",
  "link": "/stock/product1",
  "category": "1231",
  "description": ""
}, {
  "name": "",
  "link": null,
  "ticker": "",
  "description": ""
}]

data = data.filter(cv => Object.values(cv).some(v => v == '' || v == null));

console.log(JSON.stringify(data))

Upvotes: 2

Related Questions