0

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.

3
  • you mean JSON.stringify(obj) ? Commented Feb 6, 2020 at 13:50
  • yes I want to make JSON array of object Commented Feb 6, 2020 at 13:55
  • In your implementation change {"category": key,"pass": res[key], "fail" : res[key]} to {"category": key,...res[key]} Commented Feb 6, 2020 at 13:56

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

why chosing closure [] and [].push over .map ?
@AZ_Thanks for the suggesion
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.