Getting the object’s property name

Getting the object’s property name

I was wondering if there was any way in JavaScript to loop through an object like so.
for(var i in myObject) {
// …
}

But get the name of each property like this.
for(var i in myObject) {
separateObj[myObject[i].name] = myObject[i];
}

I can’t seem to find anything like it on Google. They say to pass the names of the variables with them but this is not an option for what I am trying to achieve.
Thanks for any help you can offer.

Solutions/Answers:

Solution 1:

Use Object.keys():

var myObject = { a: 'c', b: 'a', c: 'b' };
var keyNames = Object.keys(myObject);
console.log(keyNames); // Outputs ["a","b","c"]

Object.keys() gives you an array of property names belonging to the input object.

Solution 2:

i is the name.

for(var name in obj) {
    alert(name);
    var value = obj[name];
    alert(value);
}

So you could do:

seperateObj[i] = myObject[i];

Solution 3:

Disclaimer
I misunderstood the question to be: “Can I know the property name that an object was attached to”, but chose to leave the answer since some people may end up here while searching for that.

Related:  javascript: how to get index of an object in an associative array?

No, an object could be attached to multiple properties, so it has no way of knowing its name.

var obj = {a:1};
var a = {x: obj, y: obj}

What would obj’s name be?

Are you sure you don’t just want the property name from the for loop?

for (var propName in obj) {
  console.log("Iterating through prop with name", propName, " its value is ", obj[propName])
}

Solution 4:

you can easily iterate in objects

eg: if the object is
var a = {a:’apple’, b:’ball’, c:’cat’, d:’doll’, e:’elephant’};

Object.keys(a).forEach(key => {
   console.log(key) // returns the keys in an object
   console.log(a[key])  // returns the appropriate value 
})

Solution 5:

for direct access a object property by position…
generally usefull for property [0]… so it holds info about the further…
or in node.js ‘require.cache[0]’ for the first loaded external module, etc. etc.

Object.keys( myObject )[ 0 ]
Object.keys( myObject )[ 1 ]
...
Object.keys( myObject )[ n ]

Solution 6:

To get the property of the object or the “array key” or “array index” depending on what your native language is….. Use the Object.keys() method.

Related:  Binding multiple events to a listener (without JQuery)?

Important, this is only compatible with “Modern browsers”:

So if your object is called, myObject…

var c = 0;
for(c in myObject) {
    console.log(Object.keys(myObject[c]));
}

Walla! This will definitely work in the latest firefox and ie11 and chrome…

Here is some documentation at MDN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys