Getting the object's property name [duplicate]
Asked Answered
U

13

211

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.

Urfa answered 23/11, 2010 at 19:59 Comment(4)
seperate should be separateRanchod
@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.Urfa
checked answer is incorrect, use Object.keys() method.Daysidayspring
checked answer and the Object.keys() thing do different things, so depending on what you want, either one might be right.Sapling
K
220

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.

Kristikristian answered 12/5, 2014 at 16:55 Comment(2)
More specifically, Object.keys(obj) returns an array of property names, i.e. keys, belonging to the passed in obj.Strenta
Addition, Object.keys() only return enumuable properties, Object.getOwnProperties() will return all it's propertiesInterject
F
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];
Freestone answered 23/11, 2010 at 20:1 Comment(4)
Object properties can can be accessed through the bracket syntax. obj.prop1 is the same as obj['prop1'].Freestone
A good practice is to use HasOwnProperty when using for..inTarkington
@Tarkington 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]})Ranchod
@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 ...Tarkington
R
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])
}
Ranchod answered 23/11, 2010 at 20:3 Comment(1)
@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.Ranchod
A
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 
})
Acumen answered 16/3, 2018 at 8:22 Comment(0)
H
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 ]
Heroin answered 18/7, 2014 at 0:43 Comment(0)
T
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]);
    
}
Thermopile answered 12/9, 2019 at 9:41 Comment(0)
D
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

Daysidayspring answered 1/5, 2015 at 14:13 Comment(0)
R
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.

Rattat answered 23/8, 2017 at 9:33 Comment(0)
P
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"]
Pasadis answered 1/3, 2018 at 11:32 Comment(1)
Be aware that this returns keys you probably don't want. e.g. an array will return length as a property name.Isle
H
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'));
Huggins answered 15/1, 2020 at 16:8 Comment(0)
A
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].

Anchovy answered 23/11, 2010 at 20:2 Comment(0)
G
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);
}
Glovsky answered 23/1, 2018 at 22:8 Comment(0)
A
-1

Quick & dirty:

function getObjName(obj) {
  return (wrap={obj}) && eval('for(p in obj){p}') && (wrap=null);
}
Absence answered 14/8, 2017 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.