在对象打字稿代码中查找元素

时间:2018-02-07 09:00:51

标签: html angular typescript object find

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

+---+-----------------+
| id|Incremental value|
+---+-----------------+
|101|   Johnis my Name|
|102|   Mikeis my Name|
|103|   Anniis my Name|
+---+-----------------+

5 个答案:

答案 0 :(得分:2)

您可以使用array.find()

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

确保声明产品

let product :any;

答案 1 :(得分:1)

你只需要使用函数“find”,如果你执行这行代码,你将获得“obtainProduct”变量中的对象,如果不存在于数组内,那么将返回值为undefined的“obtainProduct”变量。 / p>

let obtainedProduct =  this.products.find(x => x.product_id == "4");

console.log(obtaniedProduct);

答案 2 :(得分: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

答案 3 :(得分:1)

我们也可以使用过滤器。 this.employees = this.employees.filter(x =&gt; x.id == this.employeeId)[0];

答案 4 :(得分:0)

您可以使用lodash查找方法

console.log(_.find(products,{"product_id":"4"}));
相关问题