Comprehending the meaning behind the obj variable and the result of two bracket values being equivalent to {specific information within an object

There are times when even the most straightforward code seems puzzling. I recently stumbled upon a piece of JavaScript that has left me scratching my head. Despite adding a debugger to step through it, I'm still struggling to grasp its inner workings.

var obj = {};
var myID = 999;

var productID = 1;

var myModelID = 100;
var myCatID = 200;
    var addMe = 1; 

if (typeof obj[myCatID] == 'undefined') {
    obj[myCatID] = {};
}

var locationObj = {
    state: 'roch',
    city: '3',
    street: '2nd',
    houseNum: '101'
};

var qty = 1;

obj[myCatID][myModelID]={
    'location': locationObj,
    'quantity': qty,
    'prodID': productID,
    'id': myID
};

I find myself in doubt about what's happening here — `obj[myCatID][myModelID]`. It appears to involve two properties accessed using bracket notation for `obj`, followed by an object assignment. But, my understanding remains foggy.

The outcome, as shown by my alert and debugger: !https://i.sstatic.net/Sn2K5.jpg

!https://i.sstatic.net/VBRHh.jpg

If I were to inject an additional bracket value to transform `obj[myCatID][myModelID]` into `obj[myCatID][myModelID][addMe]`, why am I confronted with a debug error stating "uncaught TypeError: Cannot set property '1' of undefined" upon execution? I fail to discern how this differs from `myModelID` and its declaration. Your assistance in overcoming this hurdle is greatly appreciated.

Answer №1

If you wish to interact with JavaScript objects, you can utilize bracket accessors.

var obj = {};  // create an empty object
obj['test'] = 'Hello World';  // add a property 'test' with the value 'Hello World'
console.info(object['test']);  // Hello World
console.info(object.test);  // Hello World

It is possible to reference an object's property using either obj['propertyName'] or obj.propertyName. The same principle applies when adding a new property: obj['newProperty'] = 42 is equivalent to obj.newProperty = 42.

If you want to nest inner objects within an outer object, you can achieve this using multiple bracket accessors or dots:

obj['prop1']['prop2']['prop3'] = 42
or obj.prop1.prop2.prop3 = 42.

Note: It is essential to initialize each inner object separately before attempting to access it! Otherwise, JavaScript will throw an error stating "Cannot set property of undefined" because the targeted object has not been initialized.

var obj = {};
obj['prop1'] = {};  // creates an inner object 'prop1'
obj['prop1']['prop2']['prop3'] = 42;  // This won't work as 'prop2' hasn't been created yet

In your scenario, accessing

obj[myCatID][myModelID][addMe]</code isn't feasible since the inner object "myModelID" has not been defined. Therefore, trying to call <code>undefined['prop3']
results in an error.

The solution is simple: Verify if each inner object has been initialized previously. This is demonstrated in your code with

if (typeof obj[myCatID] == 'undefined')
.

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

"Encountering difficulties in displaying a local image through the use of require and

I've been struggling to display local images in my react app. I've tried calling the image within the render method using the require() function, like this: <img src={require('../../assets/svg/ic_planning.svg')} /> Even importin ...

Declare the push method within the Countly.q array in a TypeScript declaration file

Is there a way to declare Countly push add_event method in the following manner? Countly.q.push(['add_event',{ "key":"action_open_web", }]); I attempted to do this inside a declaration file (.d.ts) but it did not work. Here ...

How can we ensure that the user's language preference is saved?

I'm currently working on implementing a language switcher feature for a website I've been developing. I'm facing an issue where the site doesn't remember the user's language preference and keeps reverting back to English. Any ass ...

Convert HTML form input into a JSON file for safekeeping

<div class="email"> <section class="subscribe"> <div class="subscribe-pitch"> </div> <form action="#" method="post" class="subscribe-form" id="emails_form"> <input type="email" class="subscribe-input" placeholder="Enter ema ...

Inability to successfully upload batch data within specified criteria using a keyword and conditional statement

My goal is to batch the data, using "Repair" as a separator for the data. Splitting criteria = Repair Copper limit = 2.5 [ {"engineSN":"20","timeRun":"30","Cu":"2"}, {"engineSN": ...

Hyperlink to an HTML file located in a different directory and refresh the URL

Within my controller, I am managing an array of strings that represent various folder names. My goal is to retrieve the index.html file from each of these folders: $scope.folderNames = ['DCB', etc] I aim to create a link on my HTML page for eac ...

Why does Angular Material's md-select truncate the background up to the content boundary?

After updating to angular-material 0.9, I encountered an issue where the background gets cut off at the edge of the content when opening md-select. Is there a way to prevent this from happening? http://codepen.io/anon/pen/yNOypa <div class="background ...

Unable to smoothly animate object within OBJLoader

I'm a beginner in the world of Three JS and Tween JS, having recently picked it up for my project. However, I've encountered some frustration along the way. My main issue at the moment is trying to tween object1, amidst other objects like object2 ...

Utilizing precise data types for return values in React hooks with Typescript based on argument types

I developed a react hook that resembles the following structure: export const useForm = <T>(values: T) => { const [formData, setFormData] = useState<FormFieldData<T>>({}); useEffect(() => { const fields = {}; for (const ...

What is the best way to organize an array according to the positions of another array?

Currently, I am working with a tableView set to the style of Right Detail. To handle this setup, I have divided my data into two separate arrays: one for the main textLabels and another for the detailTextLabel. In this scenario, there are two sorting opti ...

Dropzone.js: Creating a personalized file explorer to include files that have already been uploaded

Don't worry, this isn't your typical "can't load files from the server" query... I'm looking to allow users to view files on the server in a bootstrap modal and then select specific files. After selection, I want to close the modal and ...

I encountered a crash in my app because of an error in my Node.js backend code that was posting the accessories and slug into the database

My node.js backend code is responsible for adding the accessory and slug to the database, but I am encountering app crashes. const express=require('express'); const Category = require("../models/Category"); const slugify=require('s ...

What is the best way to pass around shared constants within NodeJS modules?

My current approach involves the following steps: foo.js const FOO = 5; module.exports = { FOO: FOO }; I then use it in bar.js: var foo = require('foo'); foo.FOO; // 5 However, I'm wondering if there is a more efficient way to hand ...

Axios is passing an array instead of a JSON object when making a POST request

I am trying to make a post request using axios in my Vue.js front-end to communicate with Laravel on the backend. const data = { file: {id} } axios.post('api/documents/remove', data).then((response) => { ...

Encountered a problem resolving the asynchronous component rendering with View-Router

While attempting to integrate VueJs with VueRouter, I encountered a problem. The Home component is displaying the log message but not the template section. Additionally, an error was thrown as shown below: https://i.sstatic.net/2YWQL.png Home.vue <te ...

Struggling to adjust the width of a div accurately following the population of AJAX content

This particular piece of code is responsible for populating an inner div within an image slider by making an Ajax call : $.ajax({ type: "GET", dataType: 'json', url: $(this).attr('href') }).done(function (result) { ...

Modifying color in CSS for an SVG that is dynamically animated using JSON

I recently obtained an animated hamburger menu icon for free from this particular website. The animation triggers on click and reverses on the second click, functioning smoothly. Now, I am seeking guidance on changing its color using CSS. // JSON var ...

Use Javascript or Jquery to dynamically change the background color of cells in HTML tables based on their numerical

I am working with a collection of HTML tables that contain numbers presented in a specific style: <table border="1"> <tr> <th>Day</th> <th>Time</th> <th>A</th> <th>B</th> &l ...

Steps for positioning one div below another:1. Set the position property

Indeed, I am aware that this question has been asked numerous times in the past. Despite trying other solutions, none seem to resolve my issue. My objective is to have the "register" div slide down beneath the "container" div, rather than appearing next t ...

JS | How can we make an element with style=visibility:hidden become visible?

HTML: <div id="msg-text"><p><b id="msg" name="msg" style="visibility:hidden; color:#3399ff;">This is a hidden message</b></p></div> JS: $('#url').on('change keyup paste', function() { $('# ...