html - hitta element i objekt typescript-kod


I dessa produkter vill jag bara hitta elementet "product_id":"4" och visa det i vyn. Kan du hjälpa till, tack?

> 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} ]}

Svar #1

Du kan använda arrayens find-metod som visas nedan.

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

Svar #2

Du kan använda array.find()

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

se till att deklarera produkten

let product :any;