214

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.

4
  • 4
    seperate should be separate Commented Feb 29, 2012 at 22:47
  • 13
    @JuanMendes Thanks, corrected. Wow, this question is a blast from the past. I've come a 'l' + new Array(1000).join('o') + 'ng' way since then. Commented May 24, 2013 at 10:01
  • 1
    checked answer is incorrect, use Object.keys() method. Commented May 1, 2015 at 14:14
  • checked answer and the Object.keys() thing do different things, so depending on what you want, either one might be right. Commented Mar 28, 2016 at 0:42

13 Answers 13

222

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.

Sign up to request clarification or add additional context in comments.

2 Comments

More specifically, Object.keys(obj) returns an array of property names, i.e. keys, belonging to the passed in obj.
Addition, Object.keys() only return enumuable properties, Object.getOwnProperties() will return all it's properties
210

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

4 Comments

Object properties can can be accessed through the bracket syntax. obj.prop1 is the same as obj['prop1'].
A good practice is to use HasOwnProperty when using for..in
@Bakudan know what you mean, but a better way to put it is that you should use hasOwnProperty if you don't want inherited properties. That way you're not blindly following some rule. It may be that in some cases you actually do want to look at inherited properties. Another way to loop through an object's own properties is using Object.keys. Object.keys(obj).forEach(function(prop){ alert obj[prop]})
@Juan Mendes Yes, I meant the case with inherited properties. I'm forced ( sadly ) to use this approach, because IE8 does not support Object.keys ...
20

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

1 Comment

@ChadSchouggins What you said is true, but that's not the question I'm answering, because yes, you can loop through an object get each property name. I'm answering a question that may not be what the OP intended, I just wanted to clarify that multiple properties could point to the same object.
15

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

Comments

8

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 ] 

Comments

8

Other than "Object.keys( obj )", we have very simple "for...in" loop - which loops over enumerable property names of an object.

const obj = {"fName":"John","lName":"Doe"}; for (const key in obj) { //This will give key console.log(key); //This will give value console.log(obj[key]); }

Comments

4

IN ES5

E.G. you have this kind of object:

var ELEMENTS = { STEP_ELEMENT: { ID: "0", imageName: "el_0.png" }, GREEN_ELEMENT: { ID: "1", imageName: "el_1.png" }, BLUE_ELEMENT: { ID: "2", imageName: "el_2.png" }, ORANGE_ELEMENT: { ID: "3", imageName: "el_3.png" }, PURPLE_ELEMENT: { ID: "4", imageName: "el_4.png" }, YELLOW_ELEMENT: { ID: "5", imageName: "el_5.png" } }; 

And now if you want to have a function that if you pass '0' as a param - to get 'STEP_ELEMENT', if '2' to get 'BLUE_ELEMENT' and so for

function(elementId) { var element = null; Object.keys(ELEMENTS).forEach(function(key) { if(ELEMENTS[key].ID === elementId.toString()){ element = key; return; } }); return element; } 

This is probably not the best solution to the problem but its good to give you an idea how to do it.

Cheers.

Comments

3

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.

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

Comments

1

As of 2018 , You can make use of Object.getOwnPropertyNames() as described in Developer Mozilla Documentation

const object1 = { a: 1, b: 2, c: 3 }; console.log(Object.getOwnPropertyNames(object1)); // expected output: Array ["a", "b", "c"] 

1 Comment

Be aware that this returns keys you probably don't want. e.g. an array will return length as a property name.
1

Using Object.keys() function for acquiring properties from an Object, and it can help search property by name, for example:

const Products = function(){ this.Product = "Product A"; this.Price = 9.99; this.Quantity = 112; }; // Simple find function case insensitive let findPropByName = function(data, propertyName){ let props = []; Object.keys(data).forEach(element => { return props.push(element.toLowerCase()); }); console.log(props); let i = props.indexOf(propertyName.toLowerCase()); if(i > -1){ return props[i]; } return false; }; // calling the function let products = new Products(); console.log(findPropByName(products, 'quantity')); 

Comments

0

When you do the for/in loop you put up first, i is the property name. So you have the property name, i, and access the value by doing myObject[i].

Comments

0

These solutions work too.

// Solution One function removeProperty(obj, prop) { var bool; var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { if (keys[i] === prop) { delete obj[prop]; bool = true; } } return Boolean(bool); } //Solution two function removeProperty(obj, prop) { var bool; if (obj.hasOwnProperty(prop)) { bool = true; delete obj[prop]; } return Boolean(bool); } 

Comments

-1

Quick & dirty:

function getObjName(obj) { return (wrap={obj}) && eval('for(p in obj){p}') && (wrap=null); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.