【问题标题】:Is there a better way to get specific values from a JSON object?有没有更好的方法从 JSON 对象中获取特定值?
【发布时间】:2019-01-19 18:53:57
【问题描述】:

所以我试图在我的模板中显示一部电影的演员表(只有 4 名演员的姓名)。

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

这是我要返回的 JSON 对象:

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

这里,演员是一个包含 116 个对象的数组,而工作人员是 160 个。

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

{
  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"
}

我正在尝试获取“name”属性的值,即“Robert Downey Jr.”并将其显示在我的模板中。

movie.service.ts 文件

 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}`);
 }
}

我尝试过的方法:

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 cast =

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

allCast 的控制台.log =

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

this.cast 的控制台.log =

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

以上是我想要的输出。

但是,我想知道是否:

this.cast = allCast[1].map(el => el.name).slice(0, 4);

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

目前这对我有用,因为返回的 JSON 只有 3 个属性。但如果有数百个属性,就会出现问题。

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

谢谢。

【问题讨论】:

    标签: javascript arrays json object


    【解决方案1】:

    如果你不喜欢使用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);
      });
    });
    

    【讨论】:

    • 确实如此。完全没有理由在这里使用Object.values
    【解决方案2】:

    实际上,如果您只需要前 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);
    });
    

    【讨论】:

    • @VishwanathSastry 不客气,如果这对你有用,请考虑投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    相关资源
    最近更新 更多