Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access generated properties with unknown property names in array of objects [duplicate]

Using the following generated array example structure, how can I loop through and extract the property names and their associated values from each object?

[{"bg_2":"0.50"},{"bg_7":"0.10"},{"bg_12":"0.20"}]

The number of objects may change, and the property names will not be consistent.

like image 534
dijon Avatar asked Aug 14 '15 14:08

dijon


1 Answers

You can use Object.keys()[0] to get the key, then use the key to get the value.

JSFiddle

var myData = [{"bg_2":"0.50"},{"bg_7":"0.10"},{"bg_12":"0.20"}];

for (var i = 0; i < myData.length; i++) {
    var myObject = myData[i];
    var firstKey = Object.keys(myObject)[0];
    var value = myObject[firstKey];

    console.log(firstKey + ": " + value);
}

See also: ECMAScript® Language Specification: 15.2.3.14 Object.keys ( O )

like image 132
m0meni Avatar answered Oct 10 '22 18:10

m0meni