-1

So I have an API that returns JSON data

Example JSON:

{
   "result":"OK",
   "data":[
      {
         "number":"613-555-5555",
         "calls":30
      },
      {
         "number":"613-666-5555",
         "calls":100
      }
   ]
}

I am trying to output this using javascript to show the following

[number, calls],[number, calls]
var response = response.data;
var length = response.length;
alert(data[0].number);
alert(data[0].calls);

for (var i = 0; i < data.length; i++) {
    var arrayItem = data[i];
    document.write(arrayItem);
}

2 Answers2

2

This is simply a question of mapping your data to the desired format:

var final = response.data.map(function(item) {
    return [item.number, item.calls];
});
console.log(final);

Here is a demo: http://jsfiddle.net/c8UQg/

EDIT:

I didn't realise you were looking for a string representation (I thought you wanted an array). If that is the case, please disregard the above.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • for the sake of clarity in code, I'd personally be a fan of seeing `function(data){ return [data.number, data.calls];}` simply because it's easier to read. – Chase Florell Aug 01 '13 at 19:51
  • 1
    @ChaseFlorell `data` is being used to refer to a property of the original object, so I think using `data` to refer to the elements of `response.data` might be slightly confusing. I've tried to improve the naming nevertheless. – Asad Saeeduddin Aug 01 '13 at 19:56
0

If you like everything the way it is code wise, and just want to fix the error, then I suggest changing

var response = response.data;

to

var data = response.data;

Also, for the sake of debugging, change

document.write(arrayItem);

to

console.log(arrayItem);

http://jsfiddle.net/GptRW/

Chase Florell
  • 46,378
  • 57
  • 186
  • 376
  • According to the comments, that's what OP is actually doing. The question states that the calls to `alert()` work, which means that the variable name in the original code is correct. The issue is therefore most likely the call to `document.write` after the page has loaded. –  Aug 01 '13 at 19:44
  • not a fan of answering questions based on comments. The entire question should be asked in the question. Also, trying to access `data[0]` when there is no `data` object is going to be an issue beyond the `document.write` error. – Chase Florell Aug 01 '13 at 19:46