简体   繁体   English

将嵌套对象转换为对象的 Json 数组

[英]Convert nested object into Json Array of object

I want to convert nested object in Json Array.我想转换 Json 数组中的嵌套对象。
want to convert this below object想转换这个下面的对象

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

Into json array of object same as mention below进入与下面提到的相同的对象的json数组

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

I am doing this:我正在这样做:

  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);


    }

I don't know how to set pass and fail value in it.我不知道如何在其中设置通过和失败值。

You can use the function Object.entries along with the function map as follow:您可以将函数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; }

Try like this:像这样尝试:

  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
     }));
  }

Working Demo 工作演示

Try this :尝试这个 :

 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