是否有更好的方法从JSON对象获取特定值?

时间:2019-01-19 18:53:57

标签: javascript arrays json object

因此,我试图在模板中显示电影的演员表(仅4位演员的名称)。

为此,我正在调用MovieDB API并返回一个JSON对象。

这是我要返回的JSON对象:

public void buttonClick_DialogTest(View view) {

    AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);

    //  Inflate the Layout Resource file you created in Step 1
    View mView = getLayoutInflater().inflate(R.layout.timer_dialog_layout, null);

    //  Get View elements from Layout file. Be sure to include inflated view name (mView)
    final EditText mTimerMinutes = (EditText) mView.findViewById(R.id.etTimerValue);
    Button mTimerOk = (Button) mView.findViewById(R.id.btnTimerOk);
    Button mTimerCancel = (Button) mView.findViewById(R.id.btnTimerCancel);

    //  Create the AlertDialog using everything we needed from above
    mBuilder.setView(mView);
    final AlertDialog timerDialog = mBuilder.create();

    //  Set Listener for the OK Button
    mTimerOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            if (!mTimerMinutes.getText().toString().isEmpty()) {
                Toast.makeText(MainActivity.this, "You entered a Value!,", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
            }
        }
    });

    //  Set Listener for the CANCEL Button
    mTimerCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            timerDialog.dismiss();
        }
    });

    //  Finally, SHOW your Dialog!
    timerDialog.show();


    //  END OF buttonClick_DialogTest
}

在此,演员表是由116个对象组成的数组,乘员组是160个。

例如,这是强制转换数组中的第一个对象:

{id: 24578, cast: Array(116), crew: Array(160)}

我正在尝试获取“名称”属性的值,即“小罗伯特·唐尼”。并显示在我的模板中。

movie.service.ts文件

{
  cast_id: 46
  character: "Tony Stark / Iron Man"
  credit_id: "52fe4495c3a368484e02b251"
  gender: 2
  id: 3223
  name: "Robert Downey Jr."
  order: 0
  profile_path: "/1YjdSym1jTG7xjHSI0yGGWEsw5i.jpg"
}

我尝试过的方法:

 import { Injectable } from '@angular/core';
 import { HttpClient } from '@angular/common/http';

 @Injectable({
 providedIn: 'root'
 })

 export class MovieService {

 private movie_url = 'https://api.themoviedb.org/3/';
 private api_key = '52f8b1f1fd9b853d910f3fb53654d48c';
 private movie_string: string;

 constructor(public http: HttpClient) { }

 getMovie(id: number) {
 return this.http.get(`${this.movie_url}movie/${id}? 
 api_key=${this.api_key}&language=en-US`);
 }

 getCast(id: number) {
 return this.http.get(`${this.movie_url}movie/${id}/credits? 
 api_key=${this.api_key}`);
 }
}

console.log的演员=

this.movieService.getCast(id).subscribe(cast => {
  this.cast = cast;
  console.log(cast);
  const allCast = Object.values(cast);
  console.log(allCast);
  this.cast = allCast[1].map(el => el.name).slice(0, 4);
  console.log(this.cast);
  });
});

console.log of allCast =

{id: 24578, cast: Array(116), crew: Array(160) }

this.cast的console.log =

[24578, Array(116), Array(160)]

上面是我想要的输出。

但是,我想知道是否:

["Robert Downey Jr.", "Chris Evans", "Mark Ruffalo", "Chris 
Hemsworth"]

有一种更好的方法是获取“ allCast”的索引,然后在其上调用.map()。

这对我现在来说是有效的,因为返回的JSON仅具有3个属性。但是,如果有数百个属性,就会出现问题。

那么,比“ allCast [index]”更好的方法是什么?

谢谢。

2 个答案:

答案 0 :(得分:2)

如果您不喜欢使用allCast[1],则可以执行cast.cast,并摆脱allCast

this.movieService.getCast(id).subscribe(cast => {
  this.cast = cast;
  console.log(cast);
  this.cast = cast.cast.map(el => el.name).slice(0, 4);
  console.log(this.cast);
  });
});

答案 1 :(得分:1)

实际上,如果您只需要前4个names,则实际上可以先slice阵列,然后在4个长度的阵列上map(这样可以提高性能,因为您赢得了不会映射整个原始数组)。同样,无需cast就可以直接访问属性Object.values()。因此,您的代码可以简化为:

this.movieService.getCast(id).subscribe(cast =>
{
    console.log(cast);
    this.cast = cast.cast.slice(0, 4).map(el => el.name);
    console.log(this.cast);
});