Access JSON or JS property using string

In JavaScript, you can access an object property either with literal notation:

the.answer = 42;

Or with bracketed notation using a string for the property name:

the["answer"] = 42;

Those two statements do exactly the same thing, but in the case of the second one, since what goes in the brackets is a string, it can be any expression that resolves to a string (or can be coerced to one). So all of these do the same thing:

x = "answer";
the[x] = 42;

x = "ans";
y = "wer";
the[x + y] = 42;

function foo() {
    return "answer";
}
the[foo()] = 42;

…which is to set the answer property of the object the to 42.

So if description in your example can’t be a literal because it’s being passed to you from somewhere else, you can use bracketed notation:

s = "description";
_htaItems[x][s] = 'New Value';

Leave a Comment