1

When I do console.log of the following:

console.log(this.categories);

I get this structure:

enter image description here

which was created from this json from the api:

[
  {
  "id":"dff0bb3e-889f-43e6-b955-52cc7203952f",
  "name":"Wood",
  "category_types":[
     {
        "id":"49b31f43-d98d-43c8-9798-088ec6914fe5",
        "name":"Solid"
     },
     {
        "id":"8592716a-ffd5-4e97-ba9e-6a64ba6e48f1",
        "name":"Engineered"
     }
  ]
  },
  {
  "id":"6b2b6914-6c64-4389-a327-be3f08fd066d",
  "name":"Carpet",
  "category_types":[
     {
        "id":"0e2c8473-90fb-4806-a6e7-2389eeb0f9e4",
        "name":"Loop pile"
     },
     {
        "id":"3c762653-4f0d-42d2-a84e-133c7051c95b",
        "name":"Cut pile"
     },
     {
        "id":"0997d4dc-e886-46ef-83b4-d90c4fb72553",
        "name":"Cut \u0026 loop pile"
     }
  ]
  }
]

Given that I have the value 'Wood' in a string variable called value, how do I get hold of the category_types array for the Wood object?

console.log(this.categories[value]);

returns undefined.

rmcsharry
  • 5,363
  • 6
  • 65
  • 108

2 Answers2

4

You want to find object that has name of 'Wood', then get category_types. Array.prototype.find returns first value that meets the condition in the provided test function. In your case, it could look like this:

this.categories.find(value => value.name === 'Wood').category_types
Paulooze
  • 1,147
  • 10
  • 13
1

You can use Array.filter:

let wood = this.categories.filter(category => {
  return category.name === "Wood";
})[0];

This will filter your categories to retrieve the ones with name wood, then you take the first one. If you didn't find anything with name === "Wood" in your array, then it will be undefined.

Supamiu
  • 8,501
  • 7
  • 42
  • 76