How to retrieve property value in an array in javascript

685 views Asked by At

I have an array like this :

var recordings = [];


  recordings.push({
    x: e.x,
    y: e.y,
    z: e.z
  });

How can I retrieve all the values to be displayed ?

I tried :

recordings.x;
recordings.y;
recordings.z;

but it does not work

Thanks

3

There are 3 answers

0
CodingYoshi On

recordings is an array of objects. So if you want the first item, you will do it like this:

var firstItem = recordings[0];
firstItem.x;
firstItem.y;
firstItem.z;

If you want to loop through you array, you can do it like this:

recordings.forEach( function (item)
{
    var x = item.x;
    // Whatever else you need to do
});

Or like this:

for (i = 0; i < recordings.length; i++) 
{
    var x = recordings[i].x;
    // etc
}

Or if you want to use jQuery:

$.each(recordings, function(item) 
{
  var x = item.x
  // etc 
});
0
Does On

Since you put an Object into Array called recordings, you can't get value with recordings.x obviously, which is the way get value from Object.

If you want get value from Object,there is no need to push it into an array.

var e = { x: 1, y: 2, z: 3, w:4, o:5 };
var recordings = {
    x: e.x,
    y: e.y,
    z: e.z
};
console.log(recordings.x);

Otherwise, you want get value from Array , what you need is for loop.

var e = { x: 1, y: 2, z: 3, w:4, o:5 };
var recordings = [];
recordings.push({
    x: e.x,
    y: e.y,
    z: e.z
});
for(index in recordings){
    console.log(recordings[index].x);
    console.log(recordings[index].y);
    console.log(recordings[index].z);
}
0
Franck On

Thank you very much.

Here's what I was looking for

for(var i = 0; i < recordings.length; i++){
    console.log("Recording " + i + ":");
    console.log("X: " + recordings[i].x);
    console.log("Y: " + recordings[i].y);
    console.log("Z: " + recordings[i].z);
}

Or

recordings[O].x;
recordings[1].x;
recordings[2].x;
recordings[3].x;
recordings[4].x;

Thank you all again

Both solutions makes me happy