208

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
Olical
  • 39,703
  • 12
  • 54
  • 77

13 Answers13

216

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.

erikvimz
  • 5,256
  • 6
  • 44
  • 60
Trann
  • 3,539
  • 1
  • 19
  • 15
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];
Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
  • 1
    Object properties can can be accessed through the bracket syntax. obj.prop1 is the same as obj['prop1']. – Josiah Ruddell Nov 23 '10 at 20:06
  • 5
    A good practice is to use [HasOwnProperty](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/HasOwnProperty) when using for..in – Bakudan Apr 09 '12 at 04:11
  • 6
    @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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys). `Object.keys(obj).forEach(function(prop){ alert obj[prop]})` – Ruan Mendes Aug 01 '14 at 11:25
  • @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 ... – Bakudan Aug 01 '14 at 11:46
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])
}
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • @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. – Ruan Mendes Dec 01 '16 at 09:56
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 
})
Akhil Aravind
  • 5,741
  • 16
  • 35
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]);
    
}
Nikhil Vats
  • 291
  • 3
  • 7
7

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 ]
ZEE
  • 2,931
  • 5
  • 35
  • 47
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

Kevin Florida
  • 6,659
  • 3
  • 23
  • 20
3

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.

Combine
  • 3,894
  • 2
  • 27
  • 30
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"]
Aaqib
  • 9,942
  • 4
  • 21
  • 30
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'));
Ashraf Sada
  • 4,527
  • 2
  • 44
  • 48
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].

mmurch
  • 498
  • 5
  • 14
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);
}
ekbgh
  • 36
  • 3
-1

Quick & dirty:

function getObjName(obj) {
  return (wrap={obj}) && eval('for(p in obj){p}') && (wrap=null);
}
David
  • 623
  • 7
  • 16