按嵌套属性过滤数组

时间:2017-10-12 21:29:29

标签: javascript arrays

我有一个如下所示的数组:

const data = [
  {
    "id": "abc123",
    "category": {
      "id": 1,
      "name: "category1"
    },
    "otherField": "otherField1"
  },
  {
    "id": "abc234",
    "category": {
      "id": 2,
      "name: "category2"
    },
    "otherField": "otherField3"
  },
  {
    "id": "abc456",
    "category": {
      "id": 2,
      "name: "category1"
    },
    "otherField": "otherField3"
  }
]

我正在尝试按类别名称进行过滤,但控制台正在说"Cannot read property 'name' of null"

这是我的功能:

const bars = d.filter(x => x.category.name === "category1")

我试过这样的事情:

cost f = { "id": 1, "name: "category1" }
const results = d.filter(x => x.category === f)

但它只在阵列中返回1个结果。

非常感谢任何帮助!感谢。

2 个答案:

答案 0 :(得分:2)

这应解决阅读name

undefined属性的问题
const bars = d.filter(x => x && x.category && x.category.name === "category1")

如果您使用lodash / underscore

,则为另一种解决方案
const bars = d.filter(x => (_.get(x, 'category.name') === "category1"))

答案 1 :(得分:0)

您的数组中似乎存在引号问题。

此外,您无需为您的媒体资源名称使用引号。

请改用:

const data = [
  {
    id: "abc123",
    category: {
      id: 1,
      name: "category1"
    },
    otherField: "otherField1"
  },
  {
    id: "abc234",
    category: {
      id: 2,
      name: "category2"
    },
    otherField: "otherField3"
  },
  {
    id: "abc456",
    category: {
      id: 2,
      name: "category1"
    },
    otherField: "otherField3"
  }
]