简体   繁体   中英

Convert nested object into Json Array of object

I want to convert nested object in Json Array.
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

[
  { "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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM