Generating intricate JSON structures with JavaScript programming instructions

In the world of JSON, I am still a novice. I need to use JavaScript to construct the JSON structure below, but I'm struggling with adding the second element ("12101") and populating the people in the JSON Structure. Below is the code I tried, however, it does not achieve what I need:

var chat = {};
chat = {"101":{}};
chat["101"].people= {};
chat["101"].people = {"L0b12leL-Ar9GYKoAAAC":{}};
chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2c3331283b371a2b3f393274393537">[email protected]</a>"};
chat["101"].room= {};

The desired JSON structure:

{
  "101": {
    "people": {
      "L0b12leL-Ar9GYKoAAAC": {
        "name": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8dec1c3dac9c5e8d9dccdcbc086cbc7c5">[email protected]</a>",
        "inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "countrycode": "in",
        "device": "desktop",
        "roomname": "R1"
      },
      "qKCglYWI1hRhZUZCAAAD": {
        "name": "Ishim",
        "inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "roomname": "Ra"
      }
    },
    "room": {
      "f787f316-6424-491b-b779-cfc396f0f8a1": {
        "name": "R1",
        "id": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "owner": "L0b12leL-Ar9GYKoAAAC",
        "people": [
          "L0b12leL-Ar9GYKoAAAC"
        ],
        "status": "available"
      },
      "2e52905d-951c-4990-b9b7-2f3fc0602922": {
        "name": "Ra",
        "id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "owner": "qKCglYWI1hRhZUZCAAAD",
        "people": [
          "qKCglYWI1hRhZUZCAAAD"
        ],
        "status": "available"
      }
    }
  },
  "12101": {
    "people": {
      "K-Ar9GYKoAAAC": {
        "name": "Rahul.com",
        "inroom": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "owns": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "countrycode": "in",
        "device": "desktop",
        "roomname": "R1"
      },
      "I1hRhZUZCAAAD": {
        "name": "Vipul",
        "inroom": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "owns": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "roomname": "Ra"
      }
    },
    "room": {
      "b779-cfc396f0f8a1": {
        "name": "Rahul-R1",
        "id": "f787f316-6424-491b-b779-cfc396f0f8a1",
        "owner": "L0b12leL-Ar9GYKoAAAC",
        "people": [
          "L0b12leL-Ar9GYKoAAAC"
        ],
        "status": "available"
      },
      "b9b7-2f3fc0602922": {
        "name": "Vipul-Room1",
        "id": "2e52905d-951c-4990-b9b7-2f3fc0602922",
        "owner": "qKCglYWI1hRhZUZCAAAD",
        "people": [
          "qKCglYWI1hRhZUZCAAAD"
        ],
        "status": "available"
      }
    }
  }
}

Answer №1

This example is considered invalid due to the presence of dashes in the property name.

chat["101"].people.L0b12leL-Ar9GYKoAAAC = {"name":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9afb0b2abb8b499a8bcbab1f7bab6b4">[email protected]</a>"};

To correctly access this, ensure that it is enclosed within quotes

chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4137282a33202c01302422296f222e2c">[email protected]</a>"};

Answer №2

Utilize bracket notation as a property accessor like in the following example:

chat["12101"].people = {};
chat["101"].people["L0b12leL-Ar9GYKoAAAC"] = {"name":"[email protected]"};

By using bracket notation, you can easily access properties without worrying about valid identifier names. This is especially useful when working with strings like "L0b12leL-Ar9GYKoAAAC".

It's important to remember that in JSON, any string can be used as a property name as long as it is enclosed in quotes. For example, {"L0b12leL-Ar9GYKoAC":true} is just as valid as {"💖":true}.

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

Incorporate JSON information into HTML dropdown menu using Google API

I'm finding it difficult with this task. Below is a list that needs the name and address inserted into the dropdown menu from the JSON file. <div class="dropdown-list"> <div class="list-container"> <ul class="list" ...

How to present MongoDB data on the frontend using Node.js without relying on a framework

As someone with experience in HTML, CSS, and JavaScript, I am new to Node.js and server-side programming. Although I can serve HTML pages using FileSystem and the request.url stream in NodeJS, I need assistance as I navigate through my first server-side la ...

Verify the length of an array within an object using JavaScript

I am facing a problem with an object. Here is what it looks like: const array = { "entities": [ { "annexes": [ { "buildingUniqueIds": [] }, { ...

A guide on switching out an HTML element with an AJAX response

How can I dynamically replace an HTML element with Ajax response? I know how to remove the element, but I'm unsure how to then insert the new content from the Ajax call. For instance, let's say I have the following code: <ul id="products"> ...

Gson provides deserializer functionality for several data types

Deserializing a JSON response can be tricky due to the varying formats it may have. One common issue I encounter is with the "error" field, which can either be a simple boolean false or a more complex object describing the error in detail (e.g. { "code": x ...

When working with React Native, encountering an issue where passing props using the Map function results in an error stating "undefined is not a function" near the section of code involving the

Hey there! I'm currently facing an issue with fetching data from my Sanity CMS and passing it as props to a child component. Interestingly, the same code worked perfectly on another screen, but here I seem to be encountering an error. Although the dat ...

Making rapid formatting changes by rearranging the positioning of words in Javascript

Struggling to untangle my complex code, I'm unable to make the necessary adjustments. Here's what I have: var stocks= [ ["Beef (80/20) raw","oz",115.4451262,3.293742347,72,"4.85 gallons","5.65 pounds","0 - ",2.142,19,20,"0.0001275510204"," ...

The functionality of the OnClientClick event within the ASP.NET platform

While utilizing ASP.NET to pass a value to a JavaScript function, I encountered an issue where it doesn't seem to work when trying to pass a value from another control. It seems to behave as if there is a syntax error and just reverts back to the main ...

Attempting to perform recursion on two functions simultaneously may result in one of the functions being undefined

There is a page on my site that clients tend to keep open for long periods of time without refreshing, sometimes over 24 hours. Some of the actions on this page require a valid PHP session, so I created a simple set of functions to check this every 10 minu ...

Combining Multiple Models in Django Rest Framework

Recently delving into the world of Django Rest Framework and I must say, it's an amazing tool! I'm facing a bit of a roadblock with what should be a simple task - I have two models, CustomUser and Order. Each CustomUser can have zero to many Ord ...

Is there a way to create a scroll down and scroll up button that is located outside of the scroll box

A game designer challenged me to create a custom scrollbar with unique up and down button styles, as well as a custom-looking scrollbar. I wanted to achieve this without using the native browser scrollbar on Windows in Google Chrome. I attempted the follo ...

Node.js async.each triggers the error message "Callback has already been invoked"

I seem to be facing a problem that I can't pinpoint despite searching for mistakes extensively. The issue arises when async.each throws a "Callback was already called" error. Below is the code snippet where I encounter this problem: async.each(this. ...

Guide to implementing if condition within an object in React

I'm having difficulty including a condition inside an object while trying to pass data as a payload to the API. I have an object named payload and I intend to send it through the API by evaluating the value of the state named profession. const payload ...

Modifying the content of JSON key values

In my application, I am using MongoDB, Express, and MongoDB. When receiving data on the server side, it comes in the form of an array of objects (JSON) named upProbations. For example, let's say I find information about Max: [ { Name ...

How do I assign a default value to an optional parameter in a derived class in Typescript?

One of my classes is called ClientBase: export class ClientBase { constructor(private uri: string, private httpClient: HttpClient) { } // Contains Various Methods } I have multiple subclasses that are derived from the ClientBase For instance: @I ...

Failure to achieve success with jQuery Ajax

success in my AJAX call is not triggering at all, leaving me puzzled as to why. None of the alerts specified in the AJAX file are appearing. The form: <form onsubmit="check_reg();return false;" method="post" name="reg_form" id="reg"> <label ...

How to play audio with a source path that includes the special character "%" in JavaScript

Having an issue with playing an audio file that has '%' in its name. I've tried using the tag <audio src="test%320.mp3" controls></audio>, but it seems like the file is not being found when I try to play it. Can anyone ...

What is the best way to configure AngularJS for optimal integration with Google Maps services and functionalities in an "angular way"?

I'm currently working on a new app that utilizes the Google distance matrix, directions service, and various map features such as custom markers. I'm curious - where do you think is the best place to house all of this different functionality? Sho ...

Ensuring the existence of a MySQL database prior to executing a Node.js application

I am currently working on a Node.js/Express application that communicates with a MySQL server using Sequelize. I want to make sure that a particular database is created before the app starts running when using npm start. I think I need to create a one-ti ...

Javascript skips the if-else block when used asynchronously

I'm struggling with an if-else block in my code that is not getting executed as expected. Despite rearranging the code to ensure the if-else condition is met before calling http.get(), I am still facing issues. This problem arises while working with A ...