codeglove26 codeglove26 - 2 months ago 4
HTML Question

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!!

Answer

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]);
}

Comments