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

时间:2020-02-06 13:49:43

标签: javascript json angular

我想在Json Array中转换嵌套对象。
想要将其转换为下面的对象

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


    }

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

3 个答案:

答案 0 :(得分:4)

您可以按如下方式使用功能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; }

答案 1 :(得分: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
     }));
  }

Working Demo

答案 2 :(得分:0)

尝试一下:

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

相关问题