Ways to include new items in a JSON Object

I've been struggling with this issue for hours now, and I just can't seem to resolve it.

Maybe you could lend me a hand here?

Here is the JavaScript object that I have:

 var year_data = {
         "jan": [],
         "feb": [],
         "mar": [],
         "apr": [],
         "may": [],
         "jun": [],
         "jul": [],
         "aug": [],
         "sep": [],
         "oct": [],
         "nov": [],
         "dec": [],

         };

My desired result should look something like this:

var year_data= {

    jan : [
    {
        23 : [
        {
            "1" : "some text for 23",
            "2" : "some text for 23_1",
            "3" : "some text for 23_2"
        }
        ],

        26 : [
        {
            "1" : "some text for 26",
            "2" : "some text for 26_1",
            "3" : "some text for 26_2"
        }
        ]
    }
    ],



    feb : [
    {
        17 : [
        {
            "1" : "some text for 17_1",
            "2" : "some text for 17_2",
            "3" : "some text for 17_3"
        }
        ]
    }
    ],

};

I need a way to generate this object dynamically.

This is what I've tried so far:

year_data.jan.push(
    {19: [{1:"Some text for 19_1",
          2:"Some text for 19_2"}]
    }
);

After performing JSON.stringify(year_data) everything was working fine until I tried changing 19 to a variable name.

(console) Before:

{"jan":[{"19":[{"1":"Some text for 19_1","2":"Some text for 19_2"}]}],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}

Upon making the change

var current_day=19;
   year_data.jan.push(
    {current_day: [{1:"Some text for 19_1",
          2:"Some text for 19_2"}]
    }
);

I ended up with:

{"jan":[{"current_day":[{"1":"Some text for 19_1","2":"Some text for 19_2"}]}],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}

And I'm unsure of how to fix this issue.

I attempted the solution mentioned in Using a variable for a key in a JavaScript object literal

However, the outcome was:

year_data.jan[19]=[{1:"Some text for 19_1", 2:"Some text for 19_2"}];
var json=JSON.stringify(year_data);

console: {"jan":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[{"1":"Some text for 19_1","2":"Some text for 19_2"}]],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}

So, I am in need of either a workaround to achieve this

year_data.jan.push({**VARIABLE_name**: [{1:"Some text for 19_1", 2:"Some text for 19_2"}]});

or a solution to rectify this

year_data.jan[19]=[{1:"Some text for 19_1", 2:"Some text for 19_2"}];var json=JSON.stringify(year_data);

AND obtain

{"jan":[{"19":[{"1":"Some text for 19_1","2":"Some text for 19_2"}]}],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}

instead of

{"jan":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[{"1":"Some text for 19_1","2":"Some text for 19_2"}]],"feb":[],"mar":[],"apr":[],"may":[],"jun":[],"jul":[],"aug":[],"sep":[],"oct":[],"nov":[],"dec":[]}

Your assistance would be greatly appreciated!

Answer №1

Before ES6 was introduced, Javascript did not have the ability to support dynamic properties in object initializers, so you had to do it manually like this:

var current_day = 19;
var temp = {};
temp[current_day] = whatever;
year_data.jan.push(temp);

With the advent of ES6, dynamic properties are now enclosed in square brackets, as demonstrated below:

year_data.jan.push({
   [current_day]: whatever
});

Answer №2

let current_date = 19;
let data = {}; 
year_data.january.push(
    data[current_date]: [{1:"Sample text for date 19_1",
          2:"Example content for date 19_2"}]

);

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

Can the functionality of two-way data binding be achieved in Angular without utilizing ng-model and ng-bind?

During an interview, I was presented with this question which sparked my curiosity. While I have a foundational understanding of AngularJS and its ability to enable two-way data binding using ng-model and ng-bind, I am interested in exploring alternative ...

How to retrieve an array from a JSON object with JavaScript

After receiving an object from the server, I am specifically looking to extract the array ITEMS. How can I achieve this? I attempted using array['items'] but it did not yield the expected result and returned undefined { "items": [ { ...

The MeshBasicMaterial in THREE.js successfully renders, while the MeshLambertMaterial does not produce the desired outcome

In my current project, I've been working on creating a randomized sheet composed of arrays containing x, y, and z coordinates to draw triangles between points. You can see the outcome by clicking on this screenshot. Initially, I utilized MeshBasicMat ...

Creating an inline function in JavaScript for an anchor tag

I'm attempting to open a new window with a specific URL while also sharing the current page's address through an inline function. Here's what I have so far: a href="javascript:void(0);" onClick='(function() { var link = string.conc ...

The Jersey proxy client is unable to properly deserialize the JSON response into the classes generated by RAML

I have used the raml-to-jaxrs maven plugin (version 2.1.1-SNAPSHOT) to generate classes from this RAML file and I call the service using a Jersey proxy client as shown below: Client client = ClientBuilder.newClient(); Logger logger = Logger.getLogger(getC ...

Only renaming the files with Gulp, not the directories

function javascriptSites() { return gulp.src(PATHS.javascriptSites) .pipe($.sourcemaps.init()) .pipe($.babel()) .pipe($.if(PRODUCTION, $.uglify() .on('error', e => { console.log(e); }) )) .pipe($.if(PRODUCTION, $.rename({ s ...

How can I implement an alert to pop up when a user selects an option in JavaScript?

I've tried multiple solutions and searched extensively, but I can't seem to get JavaScript to alert my selected option. Why isn't it displaying an alert after selecting an option? const selects = document.querySelectorAll('.group-sel ...

Error: Unable to access property of an undefined value (ExpressJS/POST)

I have gone through all the similar questions but none of the solutions are working for me. I am facing an issue with my node js app where I am unable to print the input text from a form while using body-parser. Here is my index.ejs file: <fo ...

How can I create a redirect link in HTML that opens in a new window

I have a HTML page where I need to redirect to the next page. <a href="www.facebook.com" target="_blank">www.facebbok.com</a> Currently, it is redirecting to localhost:9000/dashboard/www.facebook.com But I only want to redirect to www.facebo ...

Unable to supersede CSS module styling using global or external stylesheets in React, Next.js, or React Native

I'm facing a challenge finding a solution to a basic issue. I have a component that is initially styled using a class from a *.module.css file. However, I want to replace this style with one from a global stylesheet or another stylesheet but I can&apo ...

jQuery may not function properly in a dynamic content environment

I'm encountering an issue with my web application. I've developed a chat feature using Ajax, and I want it to load when a button is clicked. The functionality works, but the dynamic data loaded doesn't seem to be compatible with jQuery. Aft ...

The React Component is caught in a loop of continuous re-rendering and reloading

Just starting out with React and tackling my first project. Running into a bit of trouble here, so I'm sharing my code for some insight. When users input their search term and hit 'search,' they are redirected from another page to this one. ...

Here is a unique rewrite: "Utilize jQuery to extract all data-id and amount from an HTML page, then send it through an

Is there a way to retrieve the data-id and amount values from this HTML page using jQuery? Once I have gathered that information, I would like to store it in an array and then submit it via an AJAX call. It's important to note that this is a Laravel p ...

The selector bar in Cypress does not work properly when trying to find the text 'foo' using jQuery

Having trouble with jQuery selectors in my Cypress tests. I often need to use jQuery selectors to locate elements based on text or unique generated numbers instead of using cy.contains(). Any help would be greatly appreciated! https://i.sstatic.net/FjqzJ ...

Perform the multiplication operation on two values retrieved from the API response and then calculate the total sum

I am currently pulling information from an API and I'm looking to perform a calculation on the data. Specifically, I want to multiply two different values from the response and then sum up the totals. While I already know how to sum all the values usi ...

Combining and serializing a JavaScript object

Combining nested JavaScript objects was straightforward when dealing with a single object. However, as the number of objects has increased, I require a more dynamic approach to merge the address key and serialize my object. var old = {account: "100000 ...

Aggregate functions in jq inspired by SQL GROUP BY operations (including COUNT, SUM, and more)

Previously discussed queries: Tally items under a specific key: jq count the number of items in json by a specific key Add up object values: How do I sum the values in an array of maps in jq? Inquiry How can we replicate the COUNT aggregate function to ...

The parsed JSON data is not being shared between the View Controller

I am working on parsing a series of strings from my API, including a product ID. My goal is to utilize this ID to identify the selected product in order to parse additional details in a separate detail view controller. However, I've encountered an is ...

Statement regarding Python dictionaries and lists

Can you explain the significance of the code snippet "d1=data['behavior']['process']" in Python? Given that data=json.load(f1) and d1={}. I'm struggling to grasp its meaning. ...

Spinning objects in three.js using tween.js to move around the global axis

Currently, I am working on tween-rotating a 3D cube. Thanks to this helpful post (How to rotate a object on axis world three.js?), I have successfully achieved rotation without any issues. Now, my goal is to transfer the rotation achieved through setFromRo ...