Home > Net >  Parse JSON using map() in JS
Parse JSON using map() in JS

Time:12-20

I need to get all "Need" values from such a JSON:

var body = {"payload":[
   {
      "analitic": {
         "id": 9448,
         "name": "Group"
      },
      "key": 27,
      "data": [
         {
            "id": 35368,
            "name": "sku",
            "value": "1",
            "valueId": "Need_1"
         }
      ]
   },
   {
      "analitic": {
         "id": 9448,
         "name": "Group"
      },
      "key": 110,
      "data": [
         {
            "id": 35368,
            "name": "sku",
            "value": "1",
            "valueId": "Need_2"
         }
            ]
         }      
]
   }

I think to use map () for this. Am I on the right track? And how do I get just these values? (I minified the json, there are many other fields in the original that I don't need)

UPD: The solution after studying codecademy turned out like this:

body.payload.map(function(i) {return i.data.filter(function(j) 
{return j.id == 35368}).map(function(k) 
{return k.valueId})}).join(",")

// result: "Need_1, Need_2"

CodePudding user response:

Considering your "data" key is an array with only 1 element, you can extract the need values in an array as following:

var body = {"payload":[
   {
      "analitic": {
         "id": 9448,
         "name": "Group"
      },
      "key": 27,
      "data": [
         {
            "id": 35368,
            "name": "sku",
            "value": "1",
            "valueId": "Need_1"
         }
      ]
   },
   {
      "analitic": {
         "id": 9448,
         "name": "Group"
      },
      "key": 110,
      "data": [
         {
            "id": 35368,
            "name": "sku",
            "value": "1",
            "valueId": "Need_2"
         }
            ]
         }      
]
   }
   
 var res = body['payload'].map((arr)=>arr['data'][0]['valueId']);
 console.log(res);

CodePudding user response:

The solution after studying codecademy turned out like this:

body.payload.map(function(i) {return i.data.filter(function(j) 
{return j.id == 35368}).map(function(k) 
{return k.valueId})}).join(",")

// result: "Need_1, Need_2"
  • Related