Angular2 Typescript如何从对象内部检索数组 [英] Angular2 Typescript how to retrieve an array from inside an object
本文介绍了Angular2 Typescript如何从对象内部检索数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我执行以下console.log时:
When I do console.log of the following:
console.log(this.categories);
我得到这个结构:
是通过api的json创建的
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"
}
]
}
]
鉴于我在名为value
的字符串变量中具有值'Wood',如何获取Wood对象的category_types数组?
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]);
返回未定义.
推荐答案
您要查找名称为"Wood"的对象,然后获取category_types
. Array.prototype.find
返回满足提供的测试功能中条件的第一个值.在您的情况下,可能看起来像这样:
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
这篇关于Angular2 Typescript如何从对象内部检索数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文