Getting the object's property name

Solution 1:

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 2:

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


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 ]