This question already has answers here:
Find a value in an array of objects in Javascript [duplicate]
                                
                                    (20个答案)
                                
                        
                                2年前关闭。
            
                    
当我执行以下console.log时:

console.log(this.categories);


我得到这个结构:

javascript - Angular2 Typescript如何从对象内部检索数组-LMLPHP

这是通过api的json创建的:

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


假设我在名为value的字符串变量中具有值'Wood',如何获取Wood对象的category_types数组?

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


返回未定义。

最佳答案

您要查找名称为“ Wood”的对象,然后获取category_typesArray.prototype.find返回满足提供的测试功能中条件的第一个值。在您的情况下,可能看起来像这样:

this.categories.find(value => value.name === 'Wood').category_types

07-24 09:33