在这些产品中,我只想找到元素“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);
}
}
关于html - 在对象 typescript 代码中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48659638/