When using JavaScript, the results of stringifying an array may not always align with

Can someone please assist with a strange issue I am experiencing in JavaScript?

After clicking on the 'test' link, an alert pops up displaying: "[]"

I was actually expecting to see something like: "[{'temp':25},{'thermState':'Notte'}]"

What could be causing this unexpected behavior?

<html>
<head>
    <script type="text/javascript" charset="utf-8" src="js/json2.js"></script>
    <script type="text/javascript" charset="utf-8">

    function test(){
        this.radioStates="";
        this.state = [];
        this.state["temp"]=25;
        this.state["thermState"]="Notte";
        alert(JSON.stringify(this.state));
    }

    </script>
</head>
<body>
<a href="#" onclick="test()">test</a>
</body>
</html>

Answer №1

Transform to:

let state = {}; ................

Remember, properties can only be added to objects and not arrays.

Answer №2

let data = {}; // Initialize as an empty object
data["temp"]=25;
data["thermState"]="Notte";
alert(JSON.stringify(data));

or

let dataArr = [];
dataArr[dataArr.length]= {temp: 25};
dataArr[dataArr.length]= { thermState: "Notte"};
alert(JSON.stringify(dataArr));

The first method functions like an associative array or object, while the second operates using an array of objects.

Answer №3

In order to achieve the desired output, you can use the following code:

this.state = [];
this.state[0] = { 'temp' : 25 };
this.state[1] = { 'thermState' : "Notte" };

You can view a demonstration of this code producing the expected output on jsFiddle Demo here

Let me explain why you experienced unexpected behavior.

In JavaScript, everything is treated as an object. By writing this.state = [];, you are creating an empty Array object. You can add elements to this array using this.state[number] = x or this.state.push(x).

It's important to note that JavaScript does not have associative arrays. If you write this.state["temp"]=25;, you are actually setting a property on the Array object, rather than adding an element to the array itself. This means that you can access this property using this.state.temp or this.state['temp'], but it will not be part of the array itself.

Answer №4

If you desire to have the state as an array, make sure to utilize the push method:

this.state.push({"temperature": 25, "thermostatState": "Night"});

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

Exploring the Versatility of Jsons with Retrofit and Kotlin

My API is delivering a polyphonic Json where the variable addon_item can be either a String or an Array. I have been struggling for days to create a CustomDezerializer for it, but so far, I haven't had any luck. Below is the Json response: ({ "c ...

Arrange the given data either by ID or Name and present it

Here is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <style> .content{ border: 1px solid gray; width: 250px; ...

The image data is not displaying in the $_FILES variable

I am having an issue updating an image in my database. I have a modal that loads using jQuery. When I click on the save modification button, all the form data appears except for the image file, which does not show up in the $_FILES array in PHP. I have tri ...

Different width, same height - images arranged side by side in a responsive layout

The problem lies in the images: https://i.sstatic.net/rydNO.png Here is an example of desktop resolution: https://i.sstatic.net/uv6KT.png I need to use default size pictures (800x450px) on the server. This means I have to resize and crop them with CSS to ...

Locating a user by their ID within a collection in Meteor can lead to some unexpected behavior

I have a requirement where I only want to allow users to insert a document if their email is verified. In an attempt to achieve this, I wrote the following code snippet. Events.allow({ insert: function (userId, doc) { var user = Meteor.users.f ...

Exploring the limits of AngularJS and WebSockets

After reading through this interesting article, I grasp the concept of the differences. However, I still find myself pondering the question. Is it feasible or advisable to utilize it within the same App/Website? For example, I intend to have AngularJs fetc ...

Press the button using the spacebar

I am facing an issue where I have a button with an anchor element that I need to trigger with the spacebar key for accessibility purposes. However, instead of triggering the button, pressing the spacebar causes the page to jump down when the button is in f ...

Within a single component, there are various types present when looping through an array containing objects

Hey there, I'm looking to iterate through an array containing objects with different types within a single component. operations = [ { "id": 15525205, "type": "mise_en_prep", & ...

React strict mode and Material UI console notifications

Just like a rapidly growing application can make the console as dirty as a footballer's shirt. What am I trying to convey? When using Material UI in strict mode, warnings such as FindDomNode may appear, or it may ask you to use strings instead of bo ...

Implement the morgan express middleware from exports

For my logging needs in an Express application, I have decided to utilize the morgan package. Initially, I was able to integrate morgan by using it directly in my server.js file like so: app.use(morgan('tiny')), which worked perfectly. However, I ...

Creating a basic image carousel with JavaScript, CSS, and HTML

After running the code, I encountered an issue where the first image displays but then after one second, only a white blank screen appears with no further action. It seems like there may be an error in the JavaScript code. Below is the code that was attemp ...

Pass along the value of a link upon clicking on it

I have implemented a simple list using md-data-table: <tr md-row md-select="device" md-on-select="logItem" md-auto-select="options.autoSelect" ng-repeat="device in devices.data"> <td md-cell style='text-align:left;vertical-align:middle&apo ...

embedding a CSS file specific to the location using a Firefox add-on

I am currently working on a Firefox extension project and require assistance with inserting elements and CSS into the document. I have attempted to follow tutorials on injecting a local CSS file into a webpage with a Firefox extension and inserting CSS us ...

Using Three.js to create a distorted texture video effect

Check out the example linked here for reference: In this particular project, there are two cylinders involved - an outer cylinder with an image texture and an inner cylinder with a video texture. Once the second cylinder is created and added to the scene, ...

Is there a race condition issue with jQuery Ajax?

Here is the JavaScript code I'm using to iterate through a list of textfields on a webpage. It sends the text within each textfield as a price to the server via an AJAX GET request, and then receives the parsed double value back from the server. If an ...

What is the best approach for managing generic errors in a hybrid Rails 5 app that uses a mix of JSON APIs and HTML responses?

After spending an entire day experimenting with different methods, I still haven't achieved my goal and decided to seek help now... In my Rails 5 application, I have developed a JSON API based on the actual JSON API specifications. Additionally, it f ...

PHP code for printing a JavaScript string containing a single quote

I'm encountering an issue with a script generated by PHP. When there is a single quote in the description, it throws a JavaScript error and considers the string terminated prematurely. print "<script type=\"text/javascript\">\n ...

Trouble with React Native ListView Item Visibility

I'm currently working on integrating the React Native <ListView /> component with the <List /> and <ListItem /> components from React Native Elements. However, I seem to be facing an issue where the <ListItem /> component is no ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

Implementing rowspan in PHP to display array data in a table

Seeking assistance with updating a table on a webpage to incorporate merged rows. Below is the php code responsible for processing data from a mysql database: ######## DISPLAYING TABLE WITH YEARS AND OFFICES ALONG WITH NAMES IN CELLS ######## for ...