Angular2 TypeScript如何从对象内部检索数组

20 浏览
0 Comments

Angular2 TypeScript如何从对象内部检索数组

当我使用console.log输出以下内容时:

console.log(this.categories);

我得到了这个结构:

enter image description here

这个结构是从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]);

返回undefined。

0
0 Comments

问题的出现原因:在当前的Angular项目中,无法使用Array的find方法。

解决方法:使用Array的filter方法来实现相同的功能。代码如下:

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

这段代码会过滤出数组中名称为"Wood"的category对象,并且返回第一个匹配的对象。如果在数组中找不到名称为"Wood"的对象,则返回undefined。

0
0 Comments

问题:在Angular2 Typescript中如何从对象中获取一个数组?

解决方法:

要找到名称为'Wood'的对象,然后获取category_types。使用Array.prototype.find方法可以返回满足提供的测试函数条件的第一个值。在这种情况下,代码如下:

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

0