[javascript] 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.

This question is related to javascript object properties

The answer is


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

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


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 ]

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

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

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


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'));

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.


Quick & dirty:

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

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

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


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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to properties

Property 'value' does not exist on type 'EventTarget' How to read data from java properties file using Spring Boot Kotlin - Property initialization using "by lazy" vs. "lateinit" react-router - pass props to handler component Specifying trust store information in spring boot application.properties Can I update a component's props in React.js? Property getters and setters Error in Swift class: Property not initialized at super.init call java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US How to use BeanUtils.copyProperties?