0
votes

Convertir un objet imbriqué en Json Array of Object

Je souhaite convertir un objet imbriqué dans Json Array.
je veux convertir cet objet ci-dessous

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


    }

En tableau d'objet json comme mentionné ci-dessous

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

Je fais ceci:

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

Je ne sais pas comment y définir des valeurs de réussite et d'échec.


3 commentaires

vous voulez dire JSON.stringify (obj)?


oui je veux créer un tableau d'objets JSON


Dans votre mise en œuvre, remplacez {"category": key, "pass": res [key], "fail": res [key]} par {"category": key, ... res [clé]}


3 Réponses :


4
votes

Vous pouvez utiliser la fonction Object.entries avec la fonction map comme suit:

.as-console-wrapper { max-height: 100% !important; top: 0; }
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);


0 commentaires

0
votes

Essayez comme ceci:

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

Démonstration fonctionnelle


2 commentaires

pourquoi choisir fermeture [] et [] .push plutôt que .map ?


@AZ_Merci pour la suggestion



0
votes

Essayez ceci:

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


0 commentaires