简体   繁体   English

按嵌套属性过滤数组

[英]Filter array by nested property

I have an array that looks like this: 我有一个看起来像这样的数组:

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"
  }
]

I am trying to filter by the category name, but the console is saying "Cannot read property 'name' of null" . 我正在尝试按类别名称进行过滤,但是控制台说"Cannot read property 'name' of null"

This is my function: 这是我的功能:

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

I tried something like this: 我尝试过这样的事情:

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

But it's only returning 1 result in the array. 但是它仅在数组中返回1个结果。

Any help is greatly appreciated ! 任何帮助是极大的赞赏 ! Thanks. 谢谢。

This should solve the problem of reading name property of undefined 这应该解决读取undefined name属性的问题

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

Another solution if you're using lodash/underscore 如果使用lodash /下划线,则为另一种解决方案

const bars = d.filter(x => (_.get(x, 'category.name') === "category1"))

It seems that you have a problem in your array with a quote. 看来您的报价中有问题。

Besides, there is no need to use quotes for your property names. 此外,您的属性名称无需使用引号。

Use this instead : 使用它代替:

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"
  }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM