簡體   English   中英

如何從 angular 或 javascript 中的數組中獲取對象

[英]How to get the objects from an array in angular or javascript

我有一個 object 數組,我想從數組中的“Secondiitem”中獲取對象。 我試過使用 object.keys 但它不起作用。 代碼低於https://stackblitz.com/edit/angular-pmfjux?file=src%2Fapp%2Fapp.component.ts

app.component.ts

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular";

  ngOnInit() {
    const sampleArray = [
      {
        mainitem: "My item 1",
        Seconditem: {
          createddate: "30-01-02",
          enddate: "30-01-03"
        }
      }
    ];
    // console.log(sampleArray)
    Object.keys(sampleArray.Seconditem).forEach(key => {
      console.log(key);
    });
  }
}

你不能做 sampleArray.secondItem 因為 sampleArray 是一個數組而不是 object

您必須遍歷數組以獲取數組中每個 object 的鍵

    sampleArray.forEach(x => {
      Object.keys(x.Seconditem).forEach(key => {
        console.log(key, ': ', x.SecondItem[key]);
      });
    });

我已更新此鏈接以打印 object 值https://stackblitz.com/edit/angular-cckvqe?file=src%2Fapp%2Fapp.component.ts

好吧,你的 sampleArray 是一個數組,而不是一個 object 所以你首先需要指定一個索引,你只需要添加 [0] 如下:

const item = {};

Object.keys(sampleArray[0].Seconditem).forEach(key => {
  item[key] = sampleArray[0].Seconditem[key];
});

console.log({ item });

(無論如何我不確定為什么需要數組,也許你應該將它轉換為普通的 object,或者如果它是一個數組,因為你還必須添加其他對象,比如已經存在的對象,而不是[0]你將需要一個[idx]其中idx是您循環遍歷的索引)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM