2

I'm reading data from a database and loading it in a array. When I print it to console I get something like this:

 [
 {'person.name':'name1', total:1},
 {'person.name':'name2', total:100}
 ]

So I iterate through it with this code:

for(var i=0;i<arr.length;i++){
    console.log(arr[i].total);
}

I can access the total but how can I access 'person.name'?

Hohenheimsenberg
  • 935
  • 10
  • 25
  • That isn't an array, an array would be: [{'person.name':'name1','total':1},...] To access properties of an object that has dot, spaces, minus ... in its property name you could: someArray[i]['person.name'] – HMR May 21 '13 at 05:18
  • @HMR It's an array of objects, I forgot the square brackets and the coma – Hohenheimsenberg May 21 '13 at 05:53
  • Thank you for updating the question and clear that one up as it could be confusing for future visitors to see code that isn't an array actually referred to as an array. – HMR May 21 '13 at 05:55

5 Answers5

7

Try something like:

console.log(arr[i]['person.name']);
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
5

access it like an array :

arr[i]['person.name'];

Here's more info on why/when to use this notation : JavaScript property access: dot notation vs. brackets?

Community
  • 1
  • 1
gion_13
  • 41,171
  • 10
  • 96
  • 108
2

you can use the square bracket syntax to access elements arr['person.name']

shyam
  • 9,134
  • 4
  • 29
  • 44
2
var arr = [{'person.name':'name1', total:1},
 {'person.name':'name2', total:100}]
 for(var i=0;i<arr.length;i++){
  console.log(arr[i]['person.name']);
 }
HMR
  • 37,593
  • 24
  • 91
  • 160
1

If you want to get the object keys and values from the array means you can do like this

   var arr=[{'person.name':'name1', 'total':1},{'person.name':'name2', 'total':100}]
    for(var i=0;i<arr.length;i++){
      Object.keys(arr[i]).forEach(function(key) {
           var val = arr[i][key];
          alert('key is '+key + ' value is '+val);
     });
    }
sachin
  • 13,605
  • 14
  • 42
  • 55