Fatemeh Talebi
Fatemeh Talebi

Reputation: 85

How to get JSON by specific ID in Angular

I have a JSON file with two objects like bellow:

[
  {
    "Id": 1,
    "prodList": [
      {
        "image": "assets/images/Products/cbdOil/cbd-cbg-fast-acting-therapy-all-natural-mock-up-300x300.png",
        "description": "CBD Isolate + CBG | Fast Acting Therapy | All-Natural Flavor | 1000mg",
        "price": 119.00,
        "quantity": 1
      },
      {
        "image": "assets/images/Products/cbdOil/thrive-cbd-oil-intimacy-front-300x300.png",
        "description": "Thrive CBD Intimacy Arousal Oil - 1000mg",
        "price": 95.00,
        "quantity": 1
      },
    ]
  },
  {
    "Id": 2,
    "prodList": [
      {
        "image": "assets/images/Products/balms/thrive-balm-orange-bliss-300x300.png",
        "description": "Thrive balmFull Spectrum Therapy 1000mg | Orange Bliss",
        "price": 100.00,
        "quantity": 1
      },
      {
        "image": "assets/images/Products/balms/thrive-full-spectrum-therapy-natural-300x300.png",
        "description": "Thrive CBD Full Spectrum Therapy0 | 200mg",
        "price": 175.00,
        "quantity": 1
      }
    ]
  }
]

and in my Service I get data from JSON like:

  getProducts() {
    return this.http.get('assets/productLists/Products.json')
  }

Now I want to get data by its specific Id. I have a navbar and I want to when I click on CBD Oil tab it shows the data with Id 1 and when I click on Balms shows the data with Id 2. How can I do this?

<div class="navbar">
    <li><a>CBD Oil</a></li>
    <li><a>Balms</a></li>
</div>

Upvotes: 2

Views: 998

Answers (1)

Merna Mustafa
Merna Mustafa

Reputation: 1373

You can manipulate your data as follows:
YourComponent.ts:

export class YourComponent{
  public jsonData; //get data from your service
  public myData;
  
  constructor() {}
  
  public getProductsById(id) {
    for (let i = 0; i < this.jsonData.length; i++) {
      if(this.jsonData[i]["Id"] == id){
        this.myData = this.jsonData[i].prodList;
      }
    }
  }
  public CBD(){
    this.getProductsById(1);
  }
  public Balms(){
    this.getProductsById(2);
  }
}

YourComponent.html:

<div class="navbar">
<li><a (click)="CBD()">CBD Oil</a></li>
<li><a (click)="Balms()">Balms</a></li>
</div>

<div *ngFor="let data of myData">
  <div *ngFor="let item of data | keyvalue">
    <h2>{{item.key}}</h2>
    <p>{{item.value}} </p>
  </div>
</div>

Upvotes: 1

Related Questions