如何从JS中的JSON密钥获取值?

时间:2019-03-04 03:49:20

标签: javascript typescript ionic-framework

我正在创建IONIC 4 APP,并且有一个读取这样的json的服务

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

我要将这3个值保存到单独的变量中

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() {


  }

}

我该怎么做?

3 个答案:

答案 0 :(得分:2)

再想一想,对象分解在这里也适用。

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

答案 1 :(得分:1)

您需要声明一个将接收json的变量(为了进行演示,我将其称为json_example),然后创建一个将接收键home中的项目的变量,但是,由于它是一个列表中,使用方括号确定它的“地址”,现在可以访问所需的键。

您将以类似于以下的代码结尾:

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

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

答案 2 :(得分:0)

我不认为您的ngOninit应该嵌套在构造函数中,因为那不是它的工作方式。假设您服务上的API调用方法称为getData,则可以执行以下操作:

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

    })
  }

}