Code Snippets
/

Dynamic Object Property Access Patterns

Dynamic Object Property Access Patterns

Reading and writing object properties from a string key (or an array of keys) is one of the small skills that separates clean code from a sprawl of `if/else` chains. This snippet covers bracket access with `obj[key]`, safe nested reads with optional chaining and a path walker, and destructuring with computed and renamed keys. Use these patterns when keys come from config, query strings, or user input.

JavaScript
Easy
3 snippets
js-destructuring
js-optional-chaining
references

984 views

11

const person = { name: 'Ada', age: 36, role: 'engineer' };

function get(obj, key) {
    return obj[key];
}

function set(obj, key, value) {
    obj[key] = value;
    return obj;
}

console.log(get(person, 'name')); // Ada
set(person, 'age', 37);
console.log(person.age); // 37

// Computed keys at construction time
const field = 'role';
const patch = { [field]: 'staff engineer' };
console.log(patch); // { role: 'staff engineer' }

Dot access obj.name only works when the key is a fixed identifier known at write time. As soon as the key sits in a variable, bracket access obj[key] is the only option, and it accepts any string or symbol expression. The same [field] syntax works inside an object literal to compute the key at construction time, which removes a lot of obj[field] = value follow-ups. Pull these patterns out as tiny helpers when the same lookup is repeated, but inline them otherwise so the call site stays obvious.