Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the object's property name

People also ask

How do you get the properties name of an object in typescript?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

How do I find the name of an object key?

Use object. keys(objectName) method to get access to all the keys of object.

What is it called the properties of an object?

A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object.

How do you print the properties of an object?

First way to print all properties of person object is by using Object. keys() method. In this method we pass the person object to Object. keys() as an argument.


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

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.


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

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

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 ]

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