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.

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.