0

I am creating multiple HTML elements. Elements have different properties.

I would like to get the property name, and the its value using index.

var elements = [
            {"type":"div","className":"items","id":"item-0-"+item}
            {"type":"div","className":"items","id":"item-0-"+item}
            {"type":"input","type":"number","step":1,"min":1}
        ];

I want to access it like,

        alert(elements[0][1]); //"className":"items"
        alert(elements[0][1].value); //items

I tried that but It is not working.

JMA
  • 844
  • 2
  • 11
  • 32
  • [Does JavaScript Guarantee Object Property Order?](http://stackoverflow.com/q/5525795/1529630) No. – Oriol Oct 02 '15 at 01:24

2 Answers2

0

This should allow you to see everything:

var i, j, k;
for (i = 0; i < elements.length; i++) {
     for (j in elements[i]) {
         alert(i+' '+j+' is '+elements[i][j]);
         console.log(i+' '+j+' is '+elements[i][j]); // This is less annoying than alerts
     }
}
user2182349
  • 8,572
  • 3
  • 22
  • 36
  • how to output the property name? //className – JMA Oct 02 '15 at 01:07
  • My problem is, I am going to add it in a loop, and there are different property names. Can I get the value using index? – JMA Oct 02 '15 at 01:09
0

Take a look at Object.keys():

var name = Object.keys(elements[0])[1]; // Item name = 'classname'
alert(elements[0][name]); // Item value = 'items'
rink.attendant.6
  • 36,468
  • 57
  • 89
  • 143