Getting the object's property name
Use Object.keys():
var myObject = { a: 'c', b: 'a', c: 'b' };var keyNames = Object.keys(myObject);console.log(keyNames); // Outputs ["a","b","c"]
How to get the property name of object and use that property name in javascript
The only error in your code is mapped_errors.{obj_key}.msg
. You should be using []
to access the object's property value when you are using a variable to get the key name, as mapped_errors[obj_key]
.
var mapped_errors = { _id: { location: 'body', param: '_id', value: 123, msg: '_id is required and must be a string' } };
let obj_key = Object.keys(mapped_errors);console.log(mapped_errors[obj_key].msg);
mapped_errors = { _name: { location: 'body', param: '_name', value: 123, msg: '_name is required and must be a string' } } obj_key = Object.keys(mapped_errors);console.log(mapped_errors[obj_key].msg);
get an object's property name using its value
The following simple implementation will log the keys for apple
in the console.
const alpha = {
a: 'apple',
b: 'bubble'
}
Object.entries(alpha).map(
([key, value]) => {
if (value === 'apple'){
console.log(key);
}
}
)
Get object property name as a string
Yes you can, with a little change.
function propName(prop, value){
for(var i in prop) {
if (prop[i] == value){
return i;
}
}
return false;
}
Now you can get the value like so:
var pn = propName(person,person.first_name);
// pn = "first_name";
Note I am not sure what it can be used for.
Other Note wont work very well with nested objects. but then again, see the first note.
Get Property names From Objects | JavaScript
I am not sure what you want to get exactly. If you want to get the names of teh props from na object you can define a funciton like this.
function getPropNames(object) {
return Object.keys(object);
}
likewise you can get values or both too.
function getPropValues(object) {
return Object.values(object);
}
function getPropNamesAndValues(object) {
return Object.entries(object);
}
Javascript: Retrieve Object Property Names
Before we look at our options, a quick note of the four key things about properties in JavaScript:
- Objects can have properties of their own, and properties they inherit from their prototype object.
- Properties can be enumerable or non-enumerable.
- Properties can have names that are strings, or (as of ES2015/ES6) names that are
Symbol
s. - Properties cannot have names that are numbers, like 1. Sometimes we act like they do, as when we're dealing with arrays, but they don't. Standard arrays aren't really arrays at all (per the spec; JavaScript implementations are allowed to optimize when they can), and the entries in arrays are object properties whose names are strings. So
a = ['x', 'y', 'z']
defines an array with three properties whose names are"0"
,"1"
, and"2"
. When we doa[0]
to access the first one, the number0
is converted to a string. (In theory; again, the JavaScript implementation is allowed to optimize.)
All of these properties can be discovered and enumerated (even the non-enumerable ones).
You have several options for doing so:
- A
for-in
loop (spec | MDN), with or without ahasOwnProperty
guard inside the loop to differentiate between "own" and inherited properties. (Does not include properties named withSymbol
s.) Loops through the names of the properties. Object.keys
(spec | MDN) (ES5+), which returns an array of the names of an object's own, enumerable properties. (Does not include properties named withSymbol
s.)Object.getOwnPropertyNames
(spec | MDN) (ES5+), which returns an array of the names of an object's own properties, regardless of whether they're enumerable. (Does not include properties named withSymbol
s.)It was removed in ES2016.Reflect.enumerate
(spec | MDN) (ES2015+), which returns an iterator for the names of the enumerable properties of an object, including ones it inherits. (Does not include properties named withSymbol
s.)Object.getOwnPropertySymbols
(spec | MDN) (ES2015+), which returns an array of the names of an object's own properties named withSymbol
s, regardless of whether they're enumerable. (Leaves out ones named with strings.)Reflect.ownKeys
(spec | MDN) (ES2015+), which returns an array of the names of an object's own properties no matter how they're named (Symbol
or string), and whether they're enumerable or not.
As you can see, most of the operations only include properties whose names are strings, with only Object.getOwnPropertySymbols
and Reflect.ownKeys
giving us the ones named with Symbol
s.
The order of the keys is not defined (not even in ES2015) for for-in
or Object.keys
. In ES2015 and above, it is defined for the other four, by the [[OwnPropertyKeys]]
and (where applicable) [[Enumerate]]
operations. (Since ES2015 is still [as of this writing] relatively knew, it's possible not all JavaScript engines correctly implement the order yet.)
Let's look at examples. First, some setup:
// Create an object with one "own" property (plus the ones it
// inherits from Object.prototype):
var proto = {
one: 1
}
// Create an object that uses the above as its prototype
var obj = Object.create(proto);
// Add a couple of enumerable properties
obj.two = 2;
obj.three = 3;
// Add a non-enumerable property (by default, properties created
// with Object.defineProperty are non-enumerable)
Object.defineProperty(obj, "four", {
value: 4,
configurable: true,
writable: true
});
(Object.create
was added in ES5, but the version of it taking just one argument [as above] can easily be shimmed/polyfilled for obsolete JavaScript engines, like the one in IE8. Object.defineProperty
was also added in ES5, and cannot be correctly shimmed/polyfilled.)
Since most of the operations only involve properties named by strings, we're ignoring Symbol
s for now.
Once the code above runs, we have this in memory (the *
next to a name indicates it's a non-enumerable property):
+−−−−−−−−−−−−−−−−−+
Object.prototype−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−+−−>| toString* |−−>(...a function...)
| | valueOf* |−−>(...a function...)
| | hasOwnProperty* |−−>(...a function...)
| | ... |
| +−−−−−−−−−−−−−−−−−+
|
+−−−−−−−−−−−−−−−+ |
proto−−−−−−−−−−−−−−−−−−−−+−−>| [[Prototype]] |−−+
| | one: 1 |
| +−−−−−−−−−−−−−−−+
|
+−−−−−−−−−−−−−−−+ |
obj−−>| [[Prototype]] |−−+
| two: 2 |
| three: 3 |
| four*: 4 |
+−−−−−−−−−−−−−−−+
With that setup, let's look at our options:
for-in
for-in
loops through the names of all of an object's properties (including ones it inherits from its prototype) whose names are strings (leaving out any whose names are Symbol
s).
for (var name in obj) {
// name is the name of each property, so:
console.log(name + " = " + obj[name]);
}
// Create an object with one "own" property (plus the ones it// inherits from Object.prototype):var proto = { one: 1}
// Create an object that uses the above as its prototypevar obj = Object.create(proto);
// Add a couple of enumerable propertiesobj.two = 2;obj.three = 3;
// Add a non-enumerable property (by default, properties created// with Object.defineProperty are non-enumerable)Object.defineProperty(obj, "four", { value: 4, configurable: true, writable: true});
for (var name in obj) { // name is the name of each property, so: console.log(name + " = " + obj[name]);}
Get Javascript Object Property Name
When you used grep you basically created a new array with the objects that has a name "Mike" and are below 50 or equal to 50.
In your case you can loop through your new array and print the key and value.
found_names.forEach(function (obj) {
console.log('Name: ' + obj.name);
console.log('Age: ' + obj.age);
console.log('Email: ' + obj.email);
});
If you want the index(key) you can also do
found_names.forEach(function (obj, index) {
console.log('Index: ' + index);
console.log('Name: ' + obj.name);
console.log('Age: ' + obj.age);
console.log('Email: ' + obj.email);
});
Edit 2 -
If you have a dynamic object where you don't know the keys you can use what Thiago suggested and tweaking it a bit. The example below would loop through every object then would go through its data.
found_names.forEach(function (obj) {
for(key in obj){
console.log(key + ': ' + obj[key]);
}
});
Another example would be using an array like object where you loop through an object like you are looping in an array.
found_names.forEach(function (obj, index, array) {
array.forEach(function(data){
// data would be the current index
console.log(array[data]);
});
});
Here is an example on JSFiddle
Source for forEach Docs
Get object property name self reference
I am not even sure this is possible...
Good instinct! It isn't. When you do:
q(o.first);
the value of the o.first
property (1
) is passed into q
. Nothing about the object or its property is passed to q
, just the value 1
.
If you know what object the value came from, and if that object had only one property with a matching value, you could figure it out. But of course, one or both of those won't be true the vast majority of the time. In the general case, no, there's nothing to tell you that it came from o.first
.
Related Topics
How to Convert Raw JavaScript Object to a Dictionary
Why Would Multiple Simultaneous Ajax Calls to the Same ASP.NET MVC Action Cause the Browser to Block
How to Clone HTML Element Objects in JavaScript
Limited Parallelism with Async/Await in Typescript/Es7
Set Http Header for One Request
How to Apply CSS to the Elements Within an Iframe
Onclick Calling Hide-Div Function Not Working
How to Set Preview of Video File, Selecting from Input Type='File'
Saving and Loading an Image from Localstorage
Make Vuejs and Jquery Play Nice
How to Get the Index of an Object by Its Property in JavaScript
How to Terminate the Script in JavaScript
How to Insert a Character After Every N Characters in JavaScript
Completely Removing Duplicate Items from an Array
How to Display Data Values on Chart.Js