Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object: access variable property by name as string [duplicate]

If I have a javascript object that looks like below

var columns = {   left: true,   center : false,   right : false } 

and I have a function that is passed both the object, and a property name like so

//should return false var side = read_prop(columns, 'right'); 

what would the body of read_prop(object, property) look like?

like image 828
Hailwood Avatar asked Nov 23 '10 11:11

Hailwood


People also ask

How do you access object properties dynamically?

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 you access variables in objects?

Use the member-access operator ( . ) between the object variable name and the member name. If the member is Shared, you do not need a variable to access it.

How do you copy properties from one object to another in JavaScript?

assign() The Object. assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.


1 Answers

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 
like image 99
ThiefMaster Avatar answered Oct 01 '22 01:10

ThiefMaster