2

I have the below output from Postman or hitting end point(we can say).

{
  "SearchResult": {
    "total": 11,
    "resources": [
      {
        "id": "12345",
        "name": "GuestType",
        "description": "Identity group ",
      },
      {
        "id": "56789",
        "name": "Admin",
        "description": "",
      },
    ]
  }
}

I want to extract "id" and "name" from these values. I see the values are inside sub-blocks. How to extract these key-value using java-script that need to be put in "Tests" tab in postman?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
impika
  • 107
  • 3
  • 11

3 Answers3

1

var obj={
  "SearchResult": {
    "total": 11,
    "resources": [
      {
        "id": "12345",
        "name": "GuestType",
        "description": "Identity group ",
      },
      {
        "id": "56789",
        "name": "Admin",
        "description": "",
      },
    ]
  }
}


obj.SearchResult.resources.forEach((o)=>console.log(o.id,o.name));
  • Thats great. Its working. Here can you help me in assigning each value to a variable(array) and print – impika Nov 18 '19 at 11:23
  • @impika Not Clear what you are asking for..Can you please tell the exact format you want the output – Anil Kumar Moharana Nov 18 '19 at 11:27
  • 1
    I want to match the id and name separately. eg: id[0]="12345", name[0]="GuestType" similarly for id[1] and name[1] so i need the values to be assigned in array – impika Nov 18 '19 at 11:32
  • @impika Using map is the correct way if you want the result in array,It is already answered by Kamil Kiełczewski.. – Anil Kumar Moharana Nov 18 '19 at 11:56
1

Below code will return array of objects with id and name only.... Happy coding :)

let data = {
  "SearchResult":
  {
    "total": 11,
    "resources": [
      { "id": "12345", "name": "GuestType", "description": "Identity group ", },
      { "id": "56789", "name": "Admin", "description": "", }
    ]
  }
}

let ids = data.SearchResult.resources.map(obj => {
  id: obj.id,
  name: obj.name
});
Zee
  • 483
  • 3
  • 10
  • Thats great. Its working. Here can you help me in assigning each value to a variable(array) and print – impika Nov 18 '19 at 11:28
  • Could you please brief what exactly you are looking for with a code example, so it would be more easy for me to get? – Zee Nov 18 '19 at 14:03
0

Try

let ids = data.SearchResult.resources.map(obj => obj.id);
let names = data.SearchResult.resources.map(obj => obj.name);

let data={ "SearchResult": { "total": 11, "resources": [ { "id": "12345", "name": "GuestType", "description": "Identity group ", }, { "id": "56789", "name": "Admin", "description": "", }, ] } }

let ids = data.SearchResult.resources.map(obj => obj.id);
let names = data.SearchResult.resources.map(obj => obj.name);

console.log(ids);
console.log(names);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345