JavaScript object: access variable property by name as string
You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
Dynamically access object property using variable
There are two ways to access properties of an object:
- Dot notation:
something.bar
- Bracket notation:
something['bar']
The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:
var something = {
bar: 'foo'
};
var foo = 'bar';
// both x = something[foo] and something[foo] = x work as expected
console.log(something[foo]);
console.log(something.bar)
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);
How to dynamically access object property in TypeScript
"OK"
is a string, and str
is implicitly taking the type string in your code.
When you try to access an object's property, you need to use a type keyof
. TypeScript then knows you are not assigning a random string; you are assigning strings compatible with the properties (keys) for the object.
Also, since status
is a variable, not a type, you need to extract its type with typeof
.
Try:
let str = "OK" as keyof typeof status;
status[str]; // 200
or more cleanly:
type StatusKey = keyof typeof status;
let str: StatusKey = "OK";
status[str]; // 200
// and to answer the question about reversal
status[status.OK as StatusKey]; // OK
See: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#keyof-and-lookup-types
Dynamically access object properties using a variable
Make use of brackets notation
for accessing dynamic keys
var my_object = {
object1: {
key: 'value',
key2: 'value2'
},
object2: {
key: 'othervalue',
key2: 'another'
}
}
function doSomething(obj_key) {
// add a new property to the object
my_object[obj_key].new_prop = 'this_new_prop'; // using bracket notation here
}
doSomething('object1');
console.dir(my_object);
Getting a Custom Objects properties by string var
Simply use myObject['thing']
.
Related Topics
Why Does a Regexp With Global Flag Give Wrong Results
Parsing a String to a Date in JavaScript
What Is Jsonp, and Why Was It Created
Loop Through an Array in JavaScript
Remove Duplicate Values from Js Array
What Is the !! (Not Not) Operator in JavaScript
Test For Existence of Nested JavaScript Object Key
Is There a JavaScript/Jquery Dom Change Listener
What's the Meaning of "=≫" (An Arrow Formed from Equals & Greater Than) in JavaScript
How to Check If Element Is Visible After Scrolling
How to Remove All Duplicates from an Array of Objects
Methods in Es6 Objects: Using Arrow Functions
Download a File by Jquery.Ajax
How to Access the Matched Groups in a JavaScript Regular Expression
When Should I Use a Return Statement in Es6 Arrow Functions
Is It Safe to Expose Firebase APIkey to the Public