按空属性过滤数组

时间:2016-08-18 10:42:36

标签: javascript jquery

我在Ajax响应中获得了如下所示的对象数组。

{
        "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": ""
    }

我希望按warehouseLocation过滤这些对象,这意味着我只需要warehouseLocation不为空的对象。

2 个答案:

答案 0 :(得分:2)

您可以使用Array.prototype.filter功能:

var data = [{
    "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 warehouseData = data.filter(function(val) {
  return val.warehouseLocation != "";
});

答案 1 :(得分:1)

这是一个开始的例子。



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);