简体   繁体   中英

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" .

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.

Any help is greatly appreciated ! Thanks.

This should solve the problem of reading name property of undefined

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

Another solution if you're using lodash/underscore

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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