How is it possible to retrieve an object property using an array?

I would love to hear an explanation of the behavior exhibited by this code snippet:

let obj = {a:1, b:2}
let i = ['a']
console.log(obj[i])
>> 1

Isn't it interesting how even an array can be utilized to access a property within an object? It's worth mentioning that this only works when the array has a length of 1. I've made attempts to research this phenomenon, but so far, there doesn't seem to be any documentation available that clarifies why this functionality exists.

Answer №1

Property names are always either strings or symbols.

If you provide something that is not a string or symbol, it will be automatically converted to a string.

The default behavior of the toString() method for an array can be simplified as:

String.prototype.toString = function () { return this.join(","); }

Therefore, ['a'] will be converted to 'a'.

It should be noted that this conversion only works with arrays containing one element.

For arrays with more than one element, you need to have a matching value:

const o = {
    "a,b": "Hello"
}
const a = ["a", "b"];
console.log("" + a);
console.log(o[a]);


Furthermore, since any object can be transformed into a string and the toString method can be customized, unusual outcomes can be achieved:

const data = {
  "42": "Hello"
}

class Weird {
    constructor(x) {
        this.x = x;
    }
    toString() {
        return this.x + 40;
    }
}

const w = new Weird(2);
console.log(data[w]);

(It's worth mentioning that engaging in these unconventional practices is generally ill-advised as it may result in difficulties while troubleshooting your code later on).

Answer №2

let obj = {a:1, b:2}

A new object is created with two properties, a and b, each assigned to values 1 and 2.

let i = ['a']

After that, a variable called i is defined as an array containing the string 'a'.

console.log(obj[i])

This line of code will output the value corresponding to the 'a' property in the obj object because i resolves to a string due to being a single element within the array.

If you were to use obj[i[0]] instead, it would explicitly reference the first element in the array.

obj['a'] is a valid property, while obj['a,b'] is not.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching image source using Firefox add-on

I am venturing into the world of creating my initial browser extension for Firefox. Currently, I am testing it in Firefox Dev v120. I have added an image to the 'images' directory of the extension and have specified "web_accessible_resources" in ...

What are the distinctions between performing React server-side rendering on a local machine versus on a live Node.js server like IBM Bluemix?

I successfully built a basic React app with server-side rendering using a workshop git as a foundation, along with some minor tweaks. Everything works smoothly when I run it locally with NODE_ENV=server node server.js. However, my attempts to deploy the ap ...

Encountering a TypeError in Node.js: "Error - res.setHeader doesn't exist as a function"

I am attempting to retrieve JSON data from a URL, assign it to a variable, and then send it back to the client's javascript. var getJSON =require('get-json'); app.post('/json', function(req, res) { getJSON(url, function(err, ...

Issue: Hydration unsuccessful due to the initial UI not aligning with the server-rendered content

I encountered an Unhandled Runtime Error Error: Failed Hydration due to initial UI not matching server render. In my NEXT.js (tailwind CSS) Application Please provide assistance in resolving this issue. import React from "react"; import { Soc ...

Real-time data texture updates in Three.js using JavaScript

Today has been a challenging day as I try to solve what should be a simple problem. I'm working on building an audio visualizer and my goal is to store the audio data array in a texture that updates every frame. Despite following three.js documentatio ...

Wait for another user keypress event in jQuery after a 0.5 second delay

Currently, I am working on developing a live search feature for my website. In order to reduce unnecessary requests and optimize performance, I am looking to implement a simple jQuery solution (while also ensuring that there is back-end flood control in pl ...

Error: Tried to import a module but encountered a TypeError stating that it cannot read properties of undefined while trying to read 'utf16le'

Attempting to conduct a Jest test on a React component that involves importing a module called "Siwe," which facilitates signing in with Ethereum. The configuration for Jest appears as follows: module.exports = { moduleNameMapper: { "module_nam ...

Out of nowhere, an error emerged stating, "I am unable to access the 'name' property of undefined."

I am currently working on coding a Discord bot in JavaScript for a school project. However, I encountered an error while running my code that I can't seem to understand. This error never occurred before, and I suspect it might be due to a recent chang ...

Exploring the concept of multi-level arrays and the manipulation of pointers to

In my book, it mentions that when creating the multi-dimensional array char a[10][10], you should use a parameter like char a[][10] to pass the array to a function. I wonder why it is necessary to specify the length in this way. Isn't passing a doubl ...

Enhancing Vue Filtered Lists for Increased Dynamism

Currently, I am iterating through a list of items using the v-for directive. Before displaying the list, I apply a filter based on a specific value using the .filter() method. To switch between different filtered values, I utilize the v-on:click event. How ...

What is the best way to make one page disappear and replace it with a pop-up from

I am currently encountering an issue with my sign-in and registration pages. I have a pop-up page that includes both the sign-in and register tabs. When clicking on the register tab, the sign-in page is supposed to disappear and the registration page shoul ...

The issue of execution order in JavaScript Recursion with promises

In the process of developing a method for creating markup to be used in a web app's off-canvas navigation. One of the challenges I am facing is making an asynchronous callback to another service that provides children nodes for the parent menu node (r ...

What are the best practices for running node in VSCode?

$ node test.js internal/modules/cjs/loader.js:883 throw err; ^ I have exhausted all possible solutions, including checking the PATH route for Node.js, restarting, and using different files. Despite the fact that I am able to retrieve the version when ...

Is the MUI Drawer Open 20% of the Time?

One issue I'm facing is with my MUI drawer - it's supposed to close after a menu item is clicked, but sometimes, about 1 out of 5 times, it remains open. I have based my current code on a helpful post on Stack Overflow. Take a look at the code s ...

Exploring TestCafe and Testing Library: How to destructure multiple selectors with one selector

Currently facing a challenge with writing a test using testcafe and testing library. Given the site's unique characteristics, we are unable to utilize the standard testing library role with name/label queries as our tests run across 50+ different loc ...

Is it possible to simultaneously adjust the source of multiple images using JavaScript?

After conducting some research, it is evident that there are numerous inquiries regarding changing the src of an image using JavaScript. My specific need, however, is to alter the src of three images simultaneously when a button is clicked. HTML: <ul ...

What strategies are typically employed to prevent falling into the callback hell trap when working with error-back asynchronous functions in Node.JS?

As a new Node user, I've been practicing pure Node scripting without relying on third-party npm packages. However, I quickly ran into the issue of my code becoming nested with callbacks inside callbacks, making it difficult to follow. This can lead to ...

Visualizing Data with d3.js Force Chart: Integrating Images with Nodes for Dynamic Animation

After enhancing a force diagram to compare two profiles, I am faced with the challenge of getting the main node to display an image. View comparison here How can I centrally align and size the image correctly while making the thumbnail data from the JSO ...

inject the HTML content into the <div> container

Snippet: https://jsfiddle.net/x9ghz1ko/ (Includes notes.) In my HTML file, there are two distinct sections: <section class="desktop_only"> and <section class="mobile_only">. The challenge lies in positioning a JavaScript sc ...

What is the reason behind State's disappearance only after a variable has been assigned to

Currently, I am working on a file gallery with a straightforward setup. The gallery consists of a master component and two sub-components. In the image preview section, there are left and right arrows that trigger a function named "clickHandler." This func ...