Make use of unnamed array

434 views Asked by At

I am calling an API and successfully getting back an array like this:

[ {
  "absmag" : "4.85",
  "speed" : "0",
  "colorb_v" : "0.65",
  "label" : "Sun",
  "appmag" : "-26.72",
  "distance_light_years" : "0",
  "id" : "53794",
  "hipnum" : "0",
  "vy" : "0",
  "updated_at" : "49:09.3",
  "vx" : "0",
  "vz" : "0",
  "texnum" : "1",
  "plxerr" : "0",
  "created_at" : "49:09.3",
  "plx" : "0",
  "dcalc" : "0",
  "z" : "0",
  "luminosity" : "0.8913",
  "y" : "0",
  "x" : "0"
}
 ]

How can I reference each of these lines? I'd like to do something like:

var database = xml.responseText;
console.log(database.label);
4

There are 4 answers

1
R3tep On BEST ANSWER

xml.responseText is an array, you need to access on the the good index before show label :

var database = xml.responseText;
console.log(database[0].label); // Add [0] because your example is an array of one element if you have more index refer to the edit  

If the response is a string, you need to parse the response before use it :

var database = JSON.parse(xml.responseText);
console.log(database[0].label);

Edit :

If your array has more than one index, you can use a foreach loop :

database.forEach(function(el) {
    console.log(el.label);
})
0
trjast On

You could reference the label value with

var database = xml.responseText[0];  
console.log(database.label);
0
talemyn On

The key to the answer actually lies in your question . . . that value IS an array . . . a single element array, whose only element is an object. As such, you have to access the array element like an array (i.e., with an index) and then, since that lone array element is an object, you have to access the object's properties like an object (i.e., with keys).

Using your example code, that would be: console.log(database[0].label); . . . [0] gets you the first (and only) element of the database array and .label gets you the value of the "label" property of that object.

0
Tahir Ahmed On

If I understand it correctly, you are expecting the resulting array to contain not just one object as depicted by your original question, but it can contain a number of objects.

If that is correct then extending the correct answers by @R3tep, @talemyn and @trjast, a loop on top of this array should help as well, IMHO.

var database=xml.responseText;
var length=database.length;
for(var i=0;i<length;i+=1){
  console.log(database[i].label);
}

Useful?