首页 > 解决方案 > 将嵌套对象转换为对象的 Json Array

问题描述

我想转换 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);


    }

我不知道如何在其中设置通过和失败值。

标签: javascriptjsonangular

解决方案


您可以将函数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; }


推荐阅读