codeglove26
codeglove26

Reputation: 21

Javascript - Getting object's keys when object is an array of objects

I am having troubles getting key values in a block of code similar to the following:

var someArray = [];
someArray.push(objX, objY, objZ); //each of these objects pushed in have 1 key/value pair

for (var i = 0; i < someArray.length; i++) {
    switch (Object.keys(someArray[i][0])) { //Not sure that "[i][0]" is valid?
        //now set tags using Jquery
    }
}

So in the above code example I am passing in an array of objects (each object is a single key/value pair). And want to get the key of each of these so I can set the HTML tag that corresponds to each using Jquery.

Thought: just the [i] will be sufficient since the array of each object's keys will only every be 1?

Any help is appreciated!!

Upvotes: 0

Views: 137

Answers (2)

Benjamin Sch&#252;ller
Benjamin Sch&#252;ller

Reputation: 2189

Use the objects in the array as real objects.

var objX = {key: 'one', value: 'oneValue'};
var objY = {key: 'two', value: 'twoValue'};
var objZ = {key: 'three', value: 'threeValue'};

var someArray = [];
someArray.push(objX, objY, objZ); //each of these objects pushed in have 1 key/value pair

for (var i = 0; i < someArray.length; i++) {
    var obj = someArray[i];
    var key = obj.key;
    var value = obj.value;
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074829

If each object will definitely have only one enumerable property, then you can use Object.keys(someArray[i])[0] to get that property's name in your loop. Object.keys returns an array of the object's own, enumerable property names, and [0] gets the first entry from it. (And of course, someArray[i][theName] will give you the value of that property.)

Example:

var objX = {
  x: "ecks"
};
var objY = {
  y: "why"
};
var objZ = {
  z: "zee"
};
var someArray = [];
someArray.push(objX, objY, objZ);

for (var i = 0; i < someArray.length; i++) {
  var arrayEntry = someArray[i];
  var name = Object.keys(arrayEntry)[0];
  console.log(name + " is " + arrayEntry[name]);
}

Upvotes: 3

Related Questions