How to access object using dynamic key?
You can access objects like arrays:
alert(o[key]);
Accessing an object property with a dynamically-computed name
There are two ways to access properties of an object:
- Dot notation:
something.bar
- Bracket notation:
something['bar']
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)
Typescript access and assign object property by dynamic key
I managed to find a not-too-dirty workaround that works for my use case. See example below:
//solution
myObj = {
...myObj,
[myTestKey]: myObj2[myTestKey]
}
Note: myObj
is now let
instead of const
Typescript Playground
Dynamic key name inside an object
You can type hint dynamic keys by this syntax: {[key: string]: any}
, so in your case, this should get the result you're looking for:
/**
* @typedef {{
* [key: string]: [{
* method: string,
* name: string
* }]
* }} MyObject
*/
/**
* @type {MyObject}
*/
const object = {
healthcheck: [
{ method: 'get', name: 'test' }
],
users: [
{ method: 'get', name: 'auth' }
],
}
The typedef is for convenience of using the type in various places in your code, but if you need intellisense to show the full shape of the type, you can use the type directly:/**
* @param {{
* [key: string]: [{
* method: string,
* name: string
* }]
* }} routes
*/
const xt = routes => {}
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 Typescript access object key dynamically
You have to provide a type for the COLORS
object:
// Theme.ts
const COLORS: Record<string, string> = {
DEFAULT: '#172B4D',
PRIMARY: '#5E72E4',
SECONDARY: '#F7FAFC',
}
export default { COLORS };
// Other Component:
const color= 'PRIMARY';
const colorStyle = color && COLORS[color.toUpperCase()];
A working example here. Vue JS access object by dynamic key within object
<div v-for="(server, index) in servers" :key="index">
{{ Object.values(server)[0].agent.memFree }}
</div>
How to access object property with dynamic key in Typescript?
I got it working by declaring an interface like so:
interface Variant {
[key: string]: string | number | string[];
}
and then(updatedVariant as Variant)[key] = e.currentTarget.value;
My mistake was to think that key
was missing a type or something when in fact I needed an interface for updatedVariant
.
Related Topics
Problems with Circular Dependency and Oop in Angularjs
Pass Variables to JavaScript in Expressjs
Get Visitors Language & Country Code with JavaScript (Client-Side)
Object Doesn't Support This Property or Method Rails Windows 64Bit
Start HTML5 Video at a Particular Position When Loading
What Is Firebase Firestore 'Reference' Data Type Good For
Get Selected Value/Text from Select on Change
How to Catch Jquery $.Getjson (Or $.Ajax with Datatype Set to 'JSONp') Error When Using JSONp
Why Let and Var Bindings Behave Differently Using Settimeout Function
How to Access Nested JSON Data
Why Does a Simple .*? Non-Greedy Regex Greedily Include Additional Characters Before a Match
JavaScript Call Nested Function
Getting a Union of Two Arrays in JavaScript
Why Firefox Says That Window.Event Is Undefined? (Call Function with Added Event Listener)