javascript - Angular 10:如何比较两个数组
问题描述
我有两个数组,一个带有颜色,一个带有类别。
"colors": [
{
"buttonId": "color-cinder-spark-red",
"filmCategory": 1,
"name": "cinder spark red",
"previewImg": "assets/filmPreviewImg/gloss-cinder-spark-red.png",
"default": true
},
{
"buttonId": "color-gloss-red-metallic",
"filmCategory": 2,
"name": "red metallic",
"previewImg": "assets/filmPreviewImg/gloss-red-metallic.png"
},
{
"buttonId": "color-dragon-red",
"filmCategory": 3,
"name": "dragon red",
"previewImg": "assets/filmPreviewImg/gloss-dragon-red.png"
},...
数组非常大。
这里是分类:
"types": [
{
"id": 1,
"name": "Gloss",
"type": "gloss"
},
{
"id": 2,
"name": "Matte",
"type": "matte",
"default": true
},
{
"id": 3,
"name": "Satin",
"type": "satin"
},...
在颜色数组中,类别显示为 id。我需要将所选颜色的id与类别进行比较,然后获取类别的名称。在这里我将获取所选颜色的类别 id
filmTypes = filmTypes.types;
filmColors = filmColors.colors;
currentColor: any;
modalRef: BsModalRef;
constructor(private modalService: BsModalService,
private _productService: ProductService) {}
ngOnInit(): void {
const defaultColor = this.filmColors.find((c) => c.default);
this.selectColor(defaultColor);
this._productService.currentFilmColor$.subscribe((color: any) => {
this.currentColor = color.filmCategory;
console.log('color2',this.currentColor);
});
}
如何在另一个数组中比较这个 id 并获取类别名称?
解决方案
使用Array#find
.
const { name } = filmTypes.find(({ id }) => id === this.currentColor);
推荐阅读
- c - 如何在C中对文件中的数字求和
- android - 如何从android中的下拉菜单材料设计中删除下划线
- c++ - 可以声明一组指向 std::vector 的智能指针吗
在堆栈上? - javascript - textContent 和新的文本节点有什么区别?
- html - React Hooks 和 FileReader 的奇怪行为
- python - 遍历嵌套列表并对每个元素进行操作
- scala - 需要帮助实现阻塞的有界邮箱
- python - 如何从索引变量切片中获取 pyomo VarData/值?
- clojure - 如何修复“在目录中找不到 datomic”
- python - 如何从生成器对象创建命名元组列表?