Dynamically enhance the JSON root with additional value

Oh dear, I'm feeling quite perplexed right now. I created a JSON element in the following way:

var planet = {"continent": []};
planet.continent.push({name: "Asia", flag: "yes", countries: []});
planet.continent[0].countries.push({name: "Japan", capital: "Tokyo"});

This situation has raised two questions in my mind:

  1. Am I mixing arrays with JSON objects? How can I handle this without using arrays here?
  2. Is there a way to dynamically add elements to the JSON root?

As for question 2, I'm struggling because I don't know how to add elements directly to the root. I attempted the following approach, but it didn't deliver the desired result:

var index = 0;
var galaxy = {};
world.index.push({name: WA});

Therefore, I am hoping to figure out how to iterate over a previously created array and add elements accordingly.

Answer №1

Let's clear up any confusion right off the bat: true JSON must be a string that represents a JavaScript object. What you're dealing with is known as an object literal.

Now, addressing your inquiry, you can easily add elements to an object by simply using:

object.newProperty = value;

If you have reservations about using arrays, consider embracing them. They are the appropriate object type for this purpose, and no other alternative should be used in its place.

Answer №2

Begin by referring to Kolink's response. For the task at hand:

var index = 0;
var world = {};
world.index.push({name: "WA"});

It appears that you are aiming to add a property to world with the index 0. Since you are using .push(), it suggests that you want that property to be an array, which can be achieved like this:

world[index] = [];
world[index].push({name: "WA"});

By starting with an empty object for world, the structure created would look like this:

{ "0" : [ {name:"WA"} ] }

Generally speaking, when accessing an object property where the property is stored in a variable, use the [] array-style syntax. For example:

world["somePropName"]
// is equivalent to
world.somePropName
// therefore, with a variable:
var x = "somePropName";
world[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

Passing a div's ID value using AngularJS AJAX to store it in a PHP variable

I have a collection of div elements, each with a unique id. My goal is to trigger a JavaScript function when a specific div is clicked. This function should send the id value of the clicked div to PHP, assign it to a PHP variable, and then receive a respon ...

How to extract words from a dynamic router.pathname in NextJS when only the filename is displayed instead of the full path?

I'm keeping this example as straightforward as possible, but I can add more details if needed to solve the issue Currently, I am working with dynamic routes in nextJS. My application fetches data from Twitter based on the keywords entered into the dy ...

Search for the next input using jQuery, then trigger a select event on keypress excluding any buttons

Is there a way to modify my code so that when the user presses "enter", it selects the next visible input or select element, without including buttons in this selection? $(document).on('keypress', 'input, select', function (e) { if (e. ...

How can I pass a DOM element as a prop in Vue 3?

As someone who is brand new to Vue, I'm exploring the possibilities. Although it's not something I typically do, I believe achieving a similar outcome in React + JSX (untested) could look like this: render() { const el = <p>Blah <a hre ...

Issue with ServiceStack TypeSerializer.DeserializeFromString not handling C# nullable types correctly

Has a bug been identified in the ServiceStack method TypeSerializer.DeserializeFromString when handling nullable types? Is this a known issue, and if so, is there a fix or workaround available? Here is an example of code that utilizes a JsConfig scope to ...

Double your audio experience with Webaudio by playing the sound twice

While working on WebAudio experimentation, I encountered an issue with loading a sound using the JavaScript code below. function playAudio(){ var audio = document.getElementById('music'); var audioContext = new webkitAudioContext(); ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...

Utilizing an external type definition in JSDoc @typedef

I'm encountering an issue with reducing redundancy when defining my imported types. I am trying to streamline the process, but unfortunately I am running into errors. /** @typedef {import("../types/util")} util @typedef {util.mapBehaviors} m ...

Angular JS Form's Pristine feature is malfunctioning when attempting to reset

I implemented a login form on my website. After submitting the form, I clear it and set it to Pristine mode. However, the error message still persists. Below is the code for my form: <form name="loginForm" ng-submit="loginForm.$valid && login( ...

What is the best way to alternate between two CSS stylesheets when using jQuery-UI?

Just getting started with jQuery and javascript and decided to test out 2 different jQuery-ui stylesheets in a simple .html file. The goal is to have the example dialog open with the "flick" stylesheet and the datepicker within the dialog open with the "u ...

What could be the reason for the RecyclerView not displaying any content in this particular fragment?

Setting up a simple template app with a ViewPager to experiment and get acquainted with Fragments and ViewPagers was a fun learning experience. The TabbedActivity class in my app contains a fragment class called LinearFragment: public static class LinearF ...

Can we trust the accuracy of Function.prototype.toString for our needs?

Can I trust Function.prototype.toString to provide a valid javascript function string for user-defined functions? Do any popular javascript engines differ in how they represent function objects as strings? I came across this question, but it doesn't ...

Adjust dimensions of an image retrieved from a URL

Is there a way to adjust the size of the image displayed here?: var picture = new Image(); picture.src = 'http://www.example.com/images/logo.png'; picture.width = 200; //trying to change the width of the image $('canvas').css({ ...

How can a border be applied to a table created with React components?

I have been utilizing the following react component from https://www.npmjs.com/package/react-sticky-table Is there a method to incorporate a border around this component? const Row = require("react-sticky-table").Row; <Row style={{ border: 3, borderco ...

How can you avoid Ajax calls from failing due to frequent requests?

Currently, I am utilizing ajax to retrieve some data. However, I have encountered an issue where the ajax request is triggered by hovering over a button, which could potentially result in multiple requests being sent and overwhelming the server, leading to ...

Advantages and disadvantages of distinct methods for looping through HTML elements

My JS code generates HTML elements that are structured like this: <div id="container"> <div id="block_1" class="blocks"></div> <div id="block_2" class="blocks"></div> <div id="block_3" class="blocks"></di ...

The intersection of JSON and Java servlet technologies

I have created an HTML login page where users input a number. If the number matches a database entry, the user is redirected to a specific site. If the number is not found in the database, an error message is displayed. Currently, I am utilizing a Java s ...

What could be causing the misalignment of the Datepicker calendar in Material UI?

I have integrated a datepicker using the library "@mui/x-date-pickers/DatePicker". import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { Locali ...

What is the technique for choosing the parent's ID with jQuery?

When a user clicks on any team, I need to retrieve the parent's parent ID. For example, if someone clicks on a Premier League Team, I want to store the ID 2 in a variable called league_id. Here are my attempts so far: Using Closest Method $('u ...

Starting Web Server using File (file://) protocol

I'm currently using Quasar to develop a Vue SPA web app/page. For this project, the web app will only run by clicking on the index.html file generated by the Quasar packager. This package will not be distributed online or hosted on any domain. My mai ...