Explain Codes LogoExplain Codes Logo

Javascript object: access variable property by name as string

javascript
javascript-objects
property-access
dot-notation
Anton ShumikhinbyAnton Shumikhin·Dec 5, 2024
TLDR

Harness the power of bracket notation object["property"] to dynamically surf the object's properties using a string:

let obj = {a: 1, b: 2}; console.log(obj["a"]); // Surfs up! Scored a 1

This isn't just for beach bums. Whether it's properties determined dynamically at runtime or user inputs, this approach shreds the gnarliest of waves.

Using the read_prop lifesaver function

It's not always sunny in Js-beach! Dealing with undefined properties and seeking cleaner syntax? Meet your lifesaver, the read_prop function:

function read_prop(obj, prop) { return prop.split('.').reduce((o, key) => (o && o[key] !== undefined) ? o[key] : undefined, obj); }

This function is a seasoned surfer, supporting nested properties and guarding against wipeouts from undefined properties all through a dot notation string.

Handling the waves: processing variable properties

While catching a wave is straightforward, the sea has different shapes. Here are a few to keep in mind:

  1. Using variables and function results: Make the wave come to you! Use variables or even function outputs to specify property names.

    let propertyName = 'b'; console.log(obj[propertyName]); // Caught wave b! Score: 2
  2. Wipeout handling (undefined properties): Wipeouts happen, but we get back on the board. Accessing a non-extracting property returns undefined.

    console.log(obj["c"]); // Wipeout! Property c doesn't exist, dude.
  3. Riding nested waves: For nested objects, use multiple brackets to navigate through the lineup.

    let nestedObj = {a: {b: {c: 3}}}; console.log(nestedObj["a"]["b"]["c"]); // Nailed it! Inside c, scored 3
  4. Ensuring the wave is rideable (validating property names): If the property name is user-generated or external, check your gear! Always validate and sanitize to avoid unseen rocks.

  5. Catching event waves: Use event listeners with dynamic object access for the gnarliest interactive surf sessions!

Advanced wave riding: More property access

Applications get gnarly with growth, and encountering arrays within objects or needing to dynamically create property names is normal.

  • Finding pearls (arrays) in oysters (objects): Access them like a pro! If there's an array in a property, use an extra bracket to get the elements.

    let objWithArray = {data: [1, 2, 3]}; console.log(objWithArray["data"][1]); // Diving a level deeper - score is 2
  • Creating dynamic surf spots: (Dynamic Property Names): Template literals can make creating property names** a breeze

    let dynamicPropName = `property_${2}`; let objDynamic = {[dynamicPropName]: 'value'}; console.log(objDynamic[dynamicPropName]); // Caught the dynamically named wave, score: "value"

Into the wave: Patterns and best practices

Riding the patterns and adhering best practices ensure you are the ripper:

  • Consistency: Stick to your style, pick a property access style and showing it off in your project.
  • Unchangeable Spots (Read-only properties): Set properties as non-writable or immutable in hairy situations.
  • Performance: If you're accessing properties often, cache them to avoid a repeat ride.