1

I want to do something similar to this - How to get “Data” field from xhr.responseText?

But in my case I want to extract the 'id' and the 'email' fields from the response text'.

Community
  • 1
  • 1
SMG
  • 23
  • 8

2 Answers2

1

Seen as the response appears to be JSON, You would parse the response..

var j = JSON.parse(xhr.responseText);
//show header id
console.log(j.$id);
//show each email & id
j.Data.forEach(function (e) { console.log(e.email, e.$id); });
Keith
  • 22,005
  • 2
  • 27
  • 44
  • why `'$id'` and not `'id'` ? Does JS knows any _sigll_ ? – Gilles Quénot Oct 03 '16 at 18:58
  • I was looking at the example JSON, and it was $id.. but saying that I didn't need to quote the literal, and could have just done j.$id. I think I'll edit that. – Keith Oct 03 '16 at 19:02
  • OK, sorry, didn't took a look to the JSON. But, yes, J can use sigil, like does JQuery :) But this have no special meaning AFAIK – Gilles Quénot Oct 03 '16 at 19:05
  • What is the e that is passed to the function? – SMG Oct 03 '16 at 19:47
  • There is no e been passed to a function, that is a function callback. This callback is then sent to the array item Data.forEach, you can call this parameter whatever you like, eg. you might like dataItem instead. And then it would be dataItem.$id, etc. – Keith Oct 03 '16 at 19:55
  • Can I do something like this? If id==2 then only output console.log('Email is: ', item.email); Edit – SMG Oct 04 '16 at 13:58
  • yes, in my example you would just do if (e.$id === 2) console.log(e.email), you could even just ask for the first email without using forEach, by doing if (j.Data.length) console.log(j.Data[0].email); at then end the day it's all just standard javascript objects. – Keith Oct 04 '16 at 14:03
  • I am trying to do this if(e.email) === "someunqiue@gmail.com" console.log(e.id); But it gives me this error in the console- Uncaught SyntaxError: Unexpected token === – SMG Oct 04 '16 at 14:22
  • if (e.email === 'someunqiue@gmail.com') console.log(e.id); – Keith Oct 04 '16 at 14:35
0

Steps to get id and email fields:

  1. Parse the json:

    var json = JSON.parse(xhr.responseText)

    var data = json.Data

  2. Here, data is a javascript array :

    [
      {
        $id: "2",
        email: "anu@gmail.com"
      },
      {
        $id: "3",
        email: "anu@gmail.com"
      }
    ]
    
  3. For each object in the array, print $id and email:

    data.forEach(function(datum) {
      console.log('Id': datum.$id)
      console.log('Email': datum.email)
    })
    
Adheesh
  • 11
  • 3