【问题标题】:Extract an array from object从对象中提取数组
【发布时间】:2018-06-30 06:46:12
【问题描述】:

我在尝试从 object 中提取 array 时遇到问题。结构如下:

[]
  0: Array(4)
     0: 0
     1: 5
     2: 500
     3: (5) [{…}, {…}, {…}, {…}, {…}]

我已经尝试过 object.keys、for 和 foreach 循环,但我无法找到解决方案。这个例子是我使用console.log(object) 时得到的。当我输入console.log(object.length) 时,我得到0 作为输出。但类型是object。任何帮助将不胜感激。

【问题讨论】:

  • 这是一个数组,包含一个元素,也是一个数组,有4个元素。告诉我们您想要提取的什么,并展示您尝试过的内容。
  • 您能否提供JSON.stringifying 的结构,以及您要提取的结构的示例?
  • Json.stringify 给了我 {"_isScalar":false,"source":{"_isScalar":false,"source":{"_isScalar":false,"source":{"_isScalar" :false,"source":{"_isScalar":true,"value":. JBNizet 当我使用 console.log(typeof this.test_array) 它表明它是一个对象。
  • 该对象的类型是什么?添加以下代码部分:声明对象并调用 console.log
  • 听起来可能是可观察的,您可以将相关代码添加到您的问题中吗?

标签: arrays angular typescript object foreach


【解决方案1】:

我看到三级数组,你返回的对象是一个数组,索引[0]也是一个数组,那么你在索引3处有一个5的数组

试试这个:

getTests(): Observable<any[]> {
   return this.http
       .get<any[]>(this.url) 
       .map(data => data[0][3]); 

getTest().subscribe(data => {
   console.log(data);
   //If you have a public variable "test_array" you can do
   this.test_array=data;
   })

【讨论】:

    【解决方案2】:

    使用 HttpClient

    getTests(): Observable<Test[]> {
       //Your function return a Observable, forget equal to this.test.array or whatever
       return this.http
           .get<Idea[]>(this.url) //<--get, return your json
           .map(data => data[3]); //<--we change the response, instead of returning
                                  //   all the object we only return the element[3]
    
    //And you use 
    getTest().subscribe((data:Idea[])=>{
       console.log(data);
       //If you have a public variable "test_array" you can do
       this.test_array=data;
       })
    

    【讨论】:

    • 我收到一条错误消息,指出类型 'Observable' 不可分配给类型 'Observable'。
    • 将“想法”和“测试”更改为“任何”。我不知道,因为你的界面是
    • 不幸的是,它似乎不起作用:它给出了 `(data: Idea[]) => void' 类型的参数不能分配给 '(value: Idea) => 类型的参数空白'。参数 'data' 和 'value' 的类型不兼容。类型 'Idea' 不可分配给类型 'Idea[]'。 `
    猜你喜欢
    • 2020-06-08
    • 2019-03-22
    • 2019-09-20
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多