Jothi Kannan Jothi Kannan - 3 months ago 8
jQuery Question

Filter array by empty property

I am getting an array of objects as below in my Ajax response.

{
"id": 2,
"name": "An ice sculpture",
"price": 12.50,
"tags": ["cold", "ice"],
"dimensions": {
"length": 7.0,
"width": 12.0,
"height": 9.5
},
"warehouseLocation": {
"latitude": -78.75,
"longitude": 20.4
}
},
{
"id": 3,
"name": "A blue mouse",
"price": 25.50,
"dimensions": {
"length": 3.1,
"width": 1.0,
"height": 1.0
},
"warehouseLocation": {
"latitude": 54.4,
"longitude": -32.7
}
}

{
"id": 3,
"name": "A blue mouse",
"price": 25.50,
"dimensions": {
"length": 3.1,
"width": 1.0,
"height": 1.0
},
"warehouseLocation": ""
}


I want to filter these objects by
warehouseLocation
which means I need only objects where
warehouseLocation
is not empty.

Answer

Here is an example to get started.

var arr = [{
  "id": 2,
  "name": "An ice sculpture",
  "price": 12.50,
  "tags": ["cold", "ice"],
  "dimensions": {
    "length": 7.0,
    "width": 12.0,
    "height": 9.5
  },
  "warehouseLocation": {
    "latitude": -78.75,
    "longitude": 20.4
  }
}, {
  "id": 3,
  "name": "A blue mouse",
  "price": 25.50,
  "dimensions": {
    "length": 3.1,
    "width": 1.0,
    "height": 1.0
  },
  "warehouseLocation": {
    "latitude": 54.4,
    "longitude": -32.7
  }
}, {
  "id": 3,
  "name": "A blue mouse",
  "price": 25.50,
  "dimensions": {
    "length": 3.1,
    "width": 1.0,
    "height": 1.0
  },
  "warehouseLocation": ""
}]

var filteredArr = arr.filter(function(val) {
  if (val.warehouseLocation == "")
    return false;
  return true;
});

console.log(filteredArr);