【问题标题】:Convert nested object into Json Array of object将嵌套对象转换为对象的 Json Array
【发布时间】:2020-02-06 13:49:43
【问题描述】:

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


    }

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

【问题讨论】:

  • 你的意思是 JSON.stringify(obj) ?
  • 是的,我想制作 JSON 对象数组
  • 在您的实现中将{"category": key,"pass": res[key], "fail" : res[key]} 更改为{"category": key,...res[key]}

标签: javascript json angular


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    试试这样:

      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

    【讨论】:

    • 为什么选择closure [] and [].push 而不是.map
    • @AZ_感谢您的建议
    【解决方案3】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 2017-06-08
      • 2018-11-23
      相关资源
      最近更新 更多