Tiago Silveira
Tiago Silveira

Reputation: 267

How to get the value from a JSON key in JS?

I Creating an IONIC 4 APP, and I have a service that reads a json like this

{
  "home": [
    {
      "internos": 1,
      "externos": 2,
      "cancelados": 3
    }
  ]
}

I want to save these 3 values into separated variables

import { Component, OnInit } from '@angular/core';
import { LoadHomeService } from './load-home.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
  eventosInternos : number // this should receive: 1 
  eventosExternos : number // this should receive: 2 
  eventosCancelados: number // this should receive: 3  

constructor(private homeService: LoadHomeService) { }

  ngOnInit() {


  }

}

How can I do that?

Upvotes: 0

Views: 86

Answers (3)

Igor Siriani
Igor Siriani

Reputation: 21

You need to declare a variable that will receive the json (I'll call it json_example for demonstration), then you create a variable that will receive the items in the key home, but, since it is a list, you use brackets to determinate it's "address" and now the keys you want are accessible.

You'll end with a code similar to this:

var variable = (<any>json_example).home[0];

var internos = variable.internos;
var externos = variable.externos;
var cancelados = variable.cancelados;

Upvotes: 1

Nithin CV
Nithin CV

Reputation: 1136

Adding one more thought, Object Destructuring will also be suitable here.

const yourResponseData = {
    "home": [
        {
            "internos": 1,
            "externos": 2,
            "cancelados": 3
        }
    ]
};

export interface Home {
        internos: number;
        externos: number;
        cancelados: number;
 }

const home: Home[] = yourResponseData.home;
// Object Destructuring
const { internos, externos, cancelados } = <Home>home[0];

Upvotes: 2

wentjun
wentjun

Reputation: 42516

I dont think your ngOninit should be nested within the constructor, as that is not how it works. Assuming that the API call method on your service is called getData, you can do something like this:

export class HomePage implements OnInit {
  eventosInternos : number // this should receive: 1 
  eventosExternos : number // this should receive: 2 
  eventosCancelados: number // this should receive: 3  

  constructor(private homeService: LoadHomeService) { 
    this.loadHomeData();
  }

  loadHomeData() {
    this.homeService.getData().subscribe(response => {
      this.eventosInternos = response['home'][0]['internos];
      this.eventosExternos = response['home'][0]['externos];
      this.eventosCancelados = response['home'][0]['cancelados];

    })
  }

}

Upvotes: 0

Related Questions