0

I have a nested json object:

{
  "51": {
    "wheels": 10,
    "id": 1,
    "name": "truck"
  },
  "55": {
    "wheels": 4,
    "id": 33,
    "name": "Car"
  },
  "88": {
    "wheels": 2,
    "id": 90,
    "name": "Bike"
  }
}

I would like to filter by ID but only return the wheels so ie.

Filter ID = 33 which would return 4.

I have tried using the .filter function but I get an error: filter is not a function which I assume is because this is not an array. I have tried to replicate using answer here:

How to filter deeply nested json by multiple attributes with vue/javascript

Without success because the json has a key (51, 55, 88) so I am stumped.

Thanks for the help in advance.

Rickin Rathatha
  • 157
  • 1
  • 2
  • 15

1 Answers1

0

You can use Object.values to convert the object into an array and then use find method on it to retrieve the specific object. Something like:

Object.values(obj).find(val => val.id === 33)?.wheels

let obj = {
  "51": {
    "wheels": 10,
    "id": 1,
    "name": "truck"
  },
  "55": {
    "wheels": 4,
    "id": 33,
    "name": "Car"
  },
  "88": {
    "wheels": 2,
    "id": 90,
    "name": "Bike"
  }
}

console.log(Object.values(obj).find(val => val.id === 33)?.wheels)
Psidom
  • 209,562
  • 33
  • 339
  • 356