Strange behavior: JS object values disappear when accessed statically

I'm feeling puzzled. The issue at hand is that an object seems to lose its values within a loop based on the method of access. When accessed through variables, everything appears to be in order. However, when using static expressions identical to the variables, the correct value is not returned. But, let's delve into the code:

THE FUNCTION ITSELF:

//Defining a function with an input parameter (inputString)
function strangeBehavior(inputString){

    //Initializing the outputObject which will be returned
    var outputObject = {PROP1: "", PROP2: ""}

    // Looping through the return-Object
    for(x in outputObject){

        // Splitting input at <PROP1> etc. 
        var res = inputString.split("<" + x.toString() + ">");
        // Further splitting "splitted input" at </PROP1> etc.
        var res2 = res[1].split("</" + x.toString() + ">");

        // res2[0] now represents the String between <PROP1></PROP1>
        outputObject.x = res2[0];

        // Logging x and the value assigned to x
        console.log("-LOOP-START--------------------------------------");
        console.log("This works fine: ");
        // This part functions properly
        console.log(x.toString() + ": " + outputObject.x);

        console.log("This doesn't work as expected: ");
        // It should be the same but it isn't
        console.log("PROP1: " + outputObject.PROP1);
        console.log("PROP2: " + outputObject.PROP2);
        console.log("-LOOP-END----------------------------------------");
    }
}

ACCESS EXAMPLE:

strangeBehavior("<PROP1>String between prop1-tags</PROP1><PROP2>Prop2-Tag-String</PROP2>");

The output shows:

PROTOCOL: -LOOP-START-------------------------------------- 
PROTOCOL: This works fine:  
PROTOCOL: PROP1: String between prop1-tags 
PROTOCOL: This doesn't work as expected:  
PROTOCOL: PROP1:  
PROTOCOL: PROP2:  
PROTOCOL: -LOOP-END---------------------------------------- 
PROTOCOL: -LOOP-START-------------------------------------- 
PROTOCOL: This works fine:  
PROTOCOL: PROP2: Prop2-Tag-String 
PROTOCOL: This doesn't work as expected:  
PROTOCOL: PROP1:  
PROTOCOL: PROP2:  
PROTOCOL: -LOOP-END---------------------------------------- 

I'm quite bewildered by this situation... It all sounds so bizarre. I really hope someone can offer some assistance.

Warm regards, OL

Answer №1

When you have the line:

outputObject.x = res2[0];

You are assigning a value to a property with the name "x" on the object, not using the value stored in the variable x itself. To achieve that, you should use brackets notation like this:

outputObject[x] = res2[0];

...and similarly when accessing it later:

console.log(x + ": " + outputObject[x]);

(No need to convert x to a string using x.toString(), as x is already treated as a string.)

In JavaScript, you can access properties either by dot notation and a property name literal (obj.foo), or by brackets notation with a property name string (obj["foo"]). In bracket notation, the string representing the property name can be the result of any expression, including a variable. So these examples are all equivalent:

obj.foo
obj["foo"]
x = "foo"; obj[x]
obj["f" + "o" + "o"]

Answer №2

It is recommended to utilize:

outputObject[ x ] = res2[0];

in place of

outputObject.x

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

Implementing initial state checks for Alpine.js checkboxes based on x-modal is not functioning properly

Upon loading alpinejs, for some reason all checkboxes become unchecked. It's perplexing and I can't figure out why. <div x-data="{ colors: [orange] }"> <input type="checkbox" value="red" x-model="co ...

What are some ways to detect if JavaScript is enabled on the client side?

In the process of creating a web application, I have structured my code to dynamically generate JavaScript functions using PHP. However, it has come to my attention that if JavaScript is disabled on the client side, my application will not function as in ...

Route parameter in JavaScript: only accept numerical values

Is it possible to restrict parameter types to only accept digits? If a letter or other character is inputted, I want to fallback to a default scenario. Below are the two attempts I've made. app.get('/multi/:num?', function (request, respons ...

Is there a way to make images load only when the navigation buttons are clicked in a scrollable (jquery tools) rather than loading all images at once?

I came across this great demo tutorial that I'm currently following: The issue with the tutorial is that it loads all the images at once, which significantly impacts performance. My goal is to have it load a set of images each time you click the arro ...

Enhance the textarea using Javascript when clicked

I am experimenting with styling my textarea using a combination of JAVASCRIPT and CSS. The goal is to make it expand in size from 20px height to 120px height when clicked, using document.getElementById("tweet_area"). However, I am facing an issue where t ...

The issue of overflow-y not functioning properly in conjunction with ng-repeat has been observed

As indicated in this resource, setting a fixed height for the div is suggested, but it seems like it's not working with the code provided below. <div style="margin-top:0.5vh;"> <div style="height:200px;border:1px solid red;overflow:au ...

Encountered a Dojo error of "TypeError {stack: (...), message: "undefined is not a function"}" when attempting to display a gif during an ajax load

I've been attempting to display a loading gif while an ajax call is in progress. However, I encountered an error at the show statement and the console displayed: TypeError {stack: (...), message: "undefined is not a function"} Here's my code sn ...

Show concealed elements above everything else

I've encountered an issue with my custom dropdown list as it displaces other elements when it appears. I want it to overlay on top of everything else, similar to the default select behavior. Despite trying to set position: relative; and z-index:100;, ...

In React and Editor.js, the forEach method in the If/Else statement is successfully adding paragraphs but not headlines. Interestingly, this issue seems to be isolated

Looking for assistance with rebuilding my dashboard to React in order to use Editor.js for blog content instead of a textarea. Currently using Editor JS as the editor. On my local machine, everything is working perfectly. I write an article, click Create ...

An error occurred due to a missing value within the forEach loop

In my JavaScript object, I am encountering an issue with a key. resolve: function () { var result = this.initialValue; console.log('initial value:',result); // 5 this.functions.forEach(function (element, index) { ...

Interactive questioning system using Javascript/jQuery for Quick Responses

Hi there! I'm new to StackOverflow and a bit of a beginner when it comes to javascript/jquery. My current project involves creating a chat interface that looks like SMS text messages. Right now, I have users inputting text and using javascript to disp ...

Maintaining the initial value of a textbox in jQuery across various focusin events

Struggling to accurately explain the process, so feel free to check out this helpful fiddle. In my form, there are several text input fields and a single submit button. The submit button becomes enabled once any of the form fields have been altered. If a ...

What is the best way to update specific values in a react multiselect component?

Within my modal, I have a form where I can edit my model. One of the fields in this form is a multi-select tag field called "tags", which is an array of objects consisting of labels and values as illustrated below. To populate this tag field, I have a dum ...

Utilizing commas in JavaScript

Hi everyone, I'm having an issue with printing the message "Invalid password, Must Contain:". The problem I'm facing is that when I write the code in JavaScript, the comma is being interpreted as an operator instead of a regular English comma. Th ...

Creating a Node.js API using express and mysql to retrieve various data including record count, page number, and implementing pagination functionality

How can I efficiently retrieve and display total_record_count, page_number, page_size, total_pages, has_more information in the response while implementing pagination given that I am limiting my query to 100 results? What would be the most effective approa ...

Replicate elements along with their events using jQuery

Every time I utilize ajax to dynamically generate new content using methods like .clone(), append(), etc., the newly created element loses all triggers and events that were programmed =( Once a copy is made, basic functionalities that work perfectly on ot ...

How to Make WebService Calls in JavaScript in ASP.NET without ScriptManager

I developed a Web service for my Asp.net project. Right now, I am accessing the service through JavaScript by including the Service in ScriptManager. However, I am looking to eliminate the need for a ScriptManager so that I can utilize it on any HTML pag ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...

Babel not functioning properly with static class property

I'm utilizing JSDOC along with all its supported npm plugins to generate comprehensive documentation. However, I've been facing difficulties when running jsdoc and parsing JSX files, as it consistently throws an error near the "=" sign as shown b ...

Tips on transforming a JSON array object into a JSON array

**Background:** I have been utilizing lodash to eliminate the empty key from my JSON data. However, upon removal of the keys, it transforms my array into an object. For instance: { "projection": "Miller", "series": [ { "mapPolygons": { ...