html - 在对象 typescript 代码中查找元素

标签 html angular typescript object find

在这些产品中,我只想找到元素“product_id”:“4”并显示在 View 中。你能帮忙吗?

> let products= [ {"product_id":"1", "product_name":"Product1",
> "description":"Product1", "default_price":50, "lastmoduserid":"31",
> "lastmoddtm":"2018-02-06T13:26:17.000Z", "active":1},
> {"product_id":"2", "product_name":"Product2",
> "description":"Product2", "default_price":60, "lastmoduserid":"31",
> "lastmoddtm":"2018-02-06T13:35:17.000Z", "active":1},
> {"product_id":"3", "product_name":"Product3",
> "description":"Product3", "default_price":80, "lastmoduserid":"31",
> "lastmoddtm":"2018-02-06T13:35:22.000Z", "active":1},
> {"product_id":"4", "product_name":"Product4",
> "description":"Product4", "default_price":100, "lastmoduserid":"31",
> "lastmoddtm":"2018-02-06T13:25:54.000Z", "active":1},
> {"product_id":"5", "product_name":"Product5",
> "description":"Product5", "default_price":120, "lastmoduserid":"31",
> "lastmoddtm":"2018-02-06T13:35:27.000Z", "active":1} ]}

最佳答案

您可以使用如下所示的数组查找方法。

this.product = this.products.find(t=>t.product_id == "4");

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  products:any;
  product:any;
  json= `[ {"product_id":"1", "product_name":"Product1",
 "description":"Product1", "default_price":50, "lastmoduserid":"31",
 "lastmoddtm":"2018-02-06T13:26:17.000Z", "active":1},
 {"product_id":"2", "product_name":"Product2",
 "description":"Product2", "default_price":60, "lastmoduserid":"31",
 "lastmoddtm":"2018-02-06T13:35:17.000Z", "active":1},
 {"product_id":"3", "product_name":"Product3",
 "description":"Product3", "default_price":80, "lastmoduserid":"31",
 "lastmoddtm":"2018-02-06T13:35:22.000Z", "active":1},
 {"product_id":"4", "product_name":"Product4",
 "description":"Product4", "default_price":100, "lastmoduserid":"31",
 "lastmoddtm":"2018-02-06T13:25:54.000Z", "active":1},
 {"product_id":"5", "product_name":"Product5",
 "description":"Product5", "default_price":120, "lastmoduserid":"31",
 "lastmoddtm":"2018-02-06T13:35:27.000Z", "active":1} ]`

 constructor(){
   this.products=JSON.parse(this.json);
   this.product = this.products.find(t=>t.product_id == "4");
   console.log(this.product);
 }
}

DEMO

关于html - 在对象 typescript 代码中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48659638/

相关文章:

java - ionic 电容器 Admob 插件 loadAd null 对象引用

javascript - 如何检查我的复选框列表是否已选中或未选中 AngularJS 2

c# - 将值从 Angular 服务应用程序发送到 C# 后端 Controller

typescript - Eslint 'rxjs/operators' 应该在项目的依赖项中列出

javascript - NVD3折线图单记录问题

Angular 库模块从模块导出组件、服务等

angular - 根据运行时标志提供 API 或模拟版本

javascript - 如何覆盖网址?

html - 如何使用 ID 定位表?

javascript 和 div,在 div 中创建图像和段落。