簡體   English   中英

將嵌套對象轉換為對象的 Json 數組

[英]Convert nested object into Json Array of object

我想轉換 Json 數組中的嵌套對象。
想轉換這個下面的對象

{
  "ErrorPage": {
    "PASS": 2
  },
  "Automated": {
    "PASS": 17,
    "FAIL": 31
  },
  "HomePage(Landing page)": {
    "PASS": 1,
    "FAIL": 6
  }
}

進入與下面提到的相同的對象的json數組

[
  { "category": "ErrorPage"
    "PASS": 2
  },
  {
    "category": "Automated" 
    "PASS": 17,
    "FAIL": 31
  },
  {
    "category": "HomePage(Landing page)" 
    "PASS": 1,
    "FAIL": 6
  }
]

我正在這樣做:

  this.httpService.getmoduleTest().subscribe((data) => {

      const res = data;
      this.Arr = Object.keys(res).map(key=>{
        return  {
          "category": key,
          "pass": res[key],
          "fail" : res[key]
        }
      }) 
      console.log(this.Arr);


    }

我不知道如何在其中設置通過和失敗值。

您可以將函數Object.entries與函數map一起使用,如下所示:

 let obj = {"ErrorPage": {"PASS": 2},"Automated": {"PASS": 17,"FAIL": 31},"HomePage(Landing page)": {"PASS": 1,"FAIL": 6}}, result = Object.entries(obj).map(([category, v]) => ({category, ...v})); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

像這樣嘗試:

  input = {
    ErrorPage: {
      PASS: 2
    },
    Automated: {
      PASS: 17,
      FAIL: 31
    },
    "HomePage(Landing page)": {
      PASS: 1,
      FAIL: 6
    }
  };
  output = [];

  constructor() {
     this.output = Object.keys(this.input).map(category => ({
        ...this.input[category],
        category
     }));
  }

工作演示

嘗試這個 :

 var jsonObj = { "ErrorPage": { "PASS": 2 }, "Automated": { "PASS": 17, "FAIL": 31 }, "HomePage(Landing page)": { "PASS": 1, "FAIL": 6 } }; var arr= []; Object.keys(jsonObj).map((item) => { arr.push({ category: item, ...jsonObj[item] }) }); console.log(arr);

暫無
暫無

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

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