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)
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);
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
Elixir - Dynamically access object property using variable
I'm assuming here that currencies
is a map, there's not really anything called an object in Elixir.
:from
is a symbol, totally unrelated to the variable from
. You should just do currencies[from]
. You can also use Map.get/3
or Map.fetch/2
to handle the case when the key is missing from the currencies
map.
How to access object property by variable in Javascript
You can split
the string and loop through it updating a variable refrencing the last found value :
let arr = [ { title: "hello", pivot: { id: 1, bid: 3 } }, { title: "home", pivot: { id: 2, bid: 3 } }, { title: "nice", pivot: { id: 3, bid: 3 } }];
let s = "0.pivot.id";
const getValue = (arr, str) => { let ref = arr; const keys = str.split(".");
keys.forEach(k => { ref = ref[k]; });
return ref;};
const result = getValue(arr, s);
console.log(result);
not able to dynamically access an object property using a variable
uniqueId
is not a property of product
so your ter
will be storing undefined
(and you should be getting an error for tar
).
When you need to use the value of a variable to access the property of an object, you need to use bracket notation.
const product = {DE2599:{name:"tet", bar:2.5, price: 3.5}};let uniqueId = 'DE2599';
console.log('with dot notation');console.log(product.uniqueId);console.log('with bracket notation');console.log(product[uniqueId]);
Dynamically access object property using passed down prop as variable, on Vue 2 & Vuex returns error
I solved it by sending all of the elements as props from the parent.
This is the child:
<template>
<tr class="stats-row">
<td :title="`${name}`">{{name}}</td>
<td>{{newCases}}</td>
<td>{{totalCases}}</td>
<td>{{newDeaths}}</td>
<td>{{totalDeaths}}</td>
<td>{{newRecovered}}</td>
<td>{{totalRecovered}}</td>
</tr>
</template>
This is the parent:
<template>
<div class="stats">
<table>
<StatsRow v-for="el in this.$store.state.countries" v-bind:key="el.name" :active="el.active" :name="el.name" :color="el.color" :showCases="el.showCases" :showDeaths="el.showDeaths" :newCases="el.newCases" :totalCases="el.totalCases" :newDeaths="el.newDeaths" :totalDeaths="el.totalDeaths" :newRecovered="el.newRecovered" :totalRecovered="el.totalRecovered"/>
</table>
</div>
</template>
Dynamically access object's Array property using variable
You can't access more than a single property at a time using dynamic property access notation. You will need to use an array of keys (often called a "path") in conjunction with Array#reduce
:
var person = { name: "Ravi", age: 25, friends: [{ name: "Suresh" }, { name: "Nitin" }, { name: "Argha" } ]}
function access (o, k) { return o[k] }
var result = ['friends', 1, 'name'].reduce(access, person)
console.log(result)
Access an object property dynamically using a variable's value ReactNative+Typescript
So there are some occasions where the other solution seems to not work, but I'll still leave it so readers can be aware of any option.
This one hasn't failed in any case, and we have no need to create an interface, so that may be a plus as well
export type MyComponentProps = {
styleName: string;
}
const MyComponent = (props: MyComponentProps) => {
const { styleName } = props;
const viewStyle = `view${styleName}`; // Possibly more readable
return (
<View
style={[
styles['container'],
`view${styleName}` == 'viewDark'
? styles['viewDark']
: {},
viewStyle == 'viewLight' // Using the more readable alternative
? styles['viewLight']
: {},
]}>
<Text
style={[
styles['text'],
`text${styleName}` == 'textDark'
? styles['textDark']
: {},
`text${styleName}` == 'textLight'
? styles['textLight']
: {},
]}>
Hello World
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
alignItems: 'center',
},
viewDark: {
backgroundColor: 'black',
},
viewLight: {
borderColor: 'white',
},
text: {
fontWeight: 'bold',
},
textDark: {
color: 'white',
},
textLight: {
color: 'black',
},
}
With the downside that we have to write the if statement manually to check if it equals each of the possible styles separately, but the upside that it appears to be more reliable
How to get object property dynamically using a custom function
A combination of reduce
and the Optional chaining operator ensures both a fail safe implementation and a fail safe access of any passed property key path at any passed type/object ...
function getValueByKeyPath(obj, path) {
return String(path)
.split('.')
.reduce((value, key) => value?.[key], Object(obj))
}
const sampleData = {
foo: {
value: 'foo',
bar: {
value: 'bar',
baz: {
value: 'baz',
},
},
},
};
console.log(
"getValueByKeyPath(sampleData, 'foo.bar.baz') ...",
getValueByKeyPath(sampleData, 'foo.bar.baz')
);
console.log(
"getValueByKeyPath(sampleData, 'foo.bar.baz.value') ...",
getValueByKeyPath(sampleData, 'foo.bar.baz.value')
);
console.log(
"\nfail safe ... getValueByKeyPath(sampleData, 'foo.biz.baz.value') ...",
getValueByKeyPath(sampleData, 'foo.biz.baz.value')
);
console.log(
"\nfail safe ... getValueByKeyPath('', 'toString') ...",
getValueByKeyPath('', 'toString')
);
console.log(
"fail safe ... getValueByKeyPath(null, '') ...",
getValueByKeyPath(null, '')
);
console.log(
"fail safe ... getValueByKeyPath() ...",
getValueByKeyPath()
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
Related Topics
How to Change the Background Color With JavaScript
Access CSS Variable from JavaScript
Detect Change in Orientation Using JavaScript
Jquery CSS Plugin That Returns Computed Style of Element to Pseudo Clone That Element
Use ≪Canvas≫ as a CSS Background
Changing Width Property of a :Before CSS Selector Using Jquery
How to Change Style of Iframe Content Cross-Domain
Trigger CSS Transition on Appended Element
How to Transform Black into Any Given Color Using Only CSS Filters
Instead of Using Prefixes I Want to Ask Site Visitors to Upgrade Their Browser
How to Disable a Browser or Element Scrollbar, But Still Allow Scrolling With Wheel or Arrow Keys
Should CSS Always Precede JavaScript
Webkit-Based Blurry/Distorted Text Post-Animation Via Translate3D
Why Is It Bad Practice to Use Links With the JavaScript: "Protocol"
Uncaught Error: Security_Err: Dom Exception 18 When I Try to Set a Cookie