javascript - 有没有更好的方法从 JSON 对象获取特定值?

标签 javascript arrays json object

所以我试图在我的模板中显示一部电影的 Actor 阵容(仅 4 名 Actor 的姓名)。

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

这是我返回的 JSON 对象:

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

这里,cast 是一个包含 116 个对象的数组,crew 是 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);
  });
});

Actor 的console.log =

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

allCast 的 console.log =

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

this.cast 的 console.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]”更好的方法呢?

谢谢。

最佳答案

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

关于javascript - 有没有更好的方法从 JSON 对象获取特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54270342/

相关文章:

javascript - 添加文本以淡入和淡出图像

javascript - Ajax 请求接收二进制数据

java - 性能原语 Array 与 ArrayList

java - 在数组中搜索特定字符串

javascript - Angular - 从工厂方法检索数据的最佳实践

javascript - PhpStorm 中 JavaScript 的第一行中断

javascript - 对于 D3 堆叠条,我如何知道鼠标位于哪个条中?

javascript - 通过搜索模式从具有多个键的数组中查找和删除

javascript - 如何显示 JSON 字符串中的特定数据?

javascript - 想要打印 json 对象的循环但无法从 json 对象访问值