Access properties with unknown property names in an array of objects

Using the following structure of an example generated array, how can I scroll and retrieve 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 property names will not be consistent.

+6
source share
2 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)

+6
source

Turning to @ AR7 answer , in case there are objects in each of them, you can cache the object returned by Object.keys() and cycle through each property in the array loop.

Using the method below, you can handle any number of properties inside an object.

I understand that this may not be more useful in this particular situation than the above answer, but I hope it will be useful to future viewers.

Jsfiddle

 var a = [ { "bg_2":"0.50", "bg_7":"0.10", "bg_12":"0.20"}, { "bg_2":"0.50", "bg_7":"0.10"}, { "bg_2":"0.50"} ]; a.forEach(function(o){ console.log(o); var k = Object.keys(o); for(var i in k) console.log(k[i], ':', o[k[i]]); }); 
+3
source

All Articles