add a JavaScript variable to a JSON data structure

My JSON object is valid and it's called list_to_book_for:

{"fold1-key1":{"name":"Van Antwerpen"},"fold2-key2":{"name":"Delporte"},"fold3-key3":{"name":"Lallemand"}}

In order to add the content of a variable into this object, I have the following structure:

"fold1":
    {
        "name": "Too book for ",
        "items":
        {

        }
    },

Is it possible to insert the variable into the items section?

Answer №1

It is certainly feasible

let y = 'my possessions';

let data = { section1: { title: "Quite heavy on ", goods: {} } };

data.section1.goods = y;

Answer №2

Of course, here is an example on how to organize JSON data:

var newJson = {"category1": {
    "title": "Awesome books", 
    "details": {} 
}}; // you can also use JSON.parse with your original json
var details = {"category1-item1":{"name":"Jane Doe"},"category2-item2":{"name":"John Smith"}};

newJson.category1.details = details;
var output = JSON.stringify(newJson); 

This code will produce the following structure:

{"category1":
    {"title":"Awesome books",
     "details":
         {"category1-item1":{"name":"Jane Doe"},
          "category2-item2":{"name":"John Smith"}
          }
    }
}

Answer №3

Maybe this could be the solution you're looking for:

for( let index in desired_list ) {
  if( desired_list.hasOwnProperty(index) ){
     new_object.categories[index] = desired_list[index];
  }
}

Answer №4

If you have a JSON object in its raw format like this:

list_to_book_for = '{"key1":{"name":"Smith"},"key2":{"name":"Johnson"},"key3":{"name":"Williams"}}';

You can convert the JSON to JavaScript using JSON.parse():

"section1": {
    "title": "To book appointment",
    "info": JSON.parse(list_to_book_for)
},

Answer №5

Big thanks to everyone who offered assistance, here's the resolution :

I establish a global variable at the beginning of the script :

    book_chain = {};

    book_chain = function()
    {
        var temp;
        $.ajax(
        {
            method:'POST',
            dataType: 'json',
            async: false,
            url:'ajax/user_list.php',
            success:function(php_response)
            {
                book_chain = php_response;
                temp = php_response;
            }
        });
        return temp;
    }();

An important detail is setting async:false

I incorporate the data into the submenu (as a JSON object) :

"fold1":
{
    "name": "Too book for ",
    "items": book_chain,
    callback: function(key, options)

Answer №6

Using the eval function is crucial for ensuring that this code operates smoothly. Here's a quick overview:

<script>
var data={"section1-key1":{"title":"Example 1"},"section2-key2":{"title":"Example 2"},"section3-key3":{"title":"Example 3"}};
var newData='{"section1": {"title": "New Title","items": { } }}';
eval('var update='+newData);
for(item in update)
{
    data[item]=update[item];
}
</script>

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

Restrict certain links from being clickable until the page has finished loading and all click events have been bound using

I developed a modal dialog plugin using jquery, designed to link to the click event of each <a> element with a specific class. This modal dialog uses AJAX to 'fetch' a page declared under the 'href' parameter of the <a> el ...

Convert XML data into a structured table format

We have an XML file named "servers.xml" that needs to be parsed. This file is located on the same server where we want it to be parsed, in the same folder. <root> <list> <server> <server name="28 Disconnects La ...

Tips for accessing jQuery UI tab elements and adjusting visibility for specific panels

How can I retrieve the panel numbers of jQuery UI tabs and adjust their visibility using CSS? I am looking to identify the panel numbers of each tab and control the visibility of certain tabs. <div id="tabs"> <ul> <li><a href="#"> ...

Navigate through a JSON object consisting of an array of dictionaries using Swift 2.1

Currently, I am working on extracting a JSON array of dictionaries and incorporating them into a custom class that will be utilized for a UITableView. The structure of the JSON data is as follows: { "inventory":[ { " ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Establishing a Table of Disarray

I've hit a roadblock and I'm feeling confused about where to go next. Currently, I'm exploring the use of JavaScript to create tables for my data and display them in HTML. While I've successfully created the HTML table, I'm facing ...

Leverage SVGs imported directly from the node_modules directory

Our architecture has been modularized by creating a node_module that contains all SVG files. Using the following code works perfectly: <q-icon> <svg> <use xlink:href="~svgmodule/svgs/icons.svg#addicon"></use> </svg> ...

Creating an Extjs model for a complex nested JSON structure

Take a look at this JSON structure { "id": 123, "name": "Ed", "orders": [ { "id": 50, "total": 100, "order_items": [ { "id": 20 ...

I am interested in building a personalized flight search form on my WordPress site

Currently, I'm in the process of developing a website for an aviation company. The WordPress site has been completed and uploaded to their hosting service. However, the client has requested that I create a custom search form and link it to their booki ...

What is causing the disparity between the JSON generated using the `Factory` and the one received from the `API`?

When I use my mock stub, the escaping works properly, but with the API response, the escaping does not seem to be applied for some reason. Here is a snippet of my Mock stub factory. require 'faker' F ...

Converting an array to an object using underscore: a beginner's guide

My array consists of different subjects: var subject = ["Tamil", "English", "Math"]; Now, I want to transform this array into an object, structured like this: [{ "name": "Tamil" }, { "name": "English" }, { "name": "Math" }] ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

Toggle class for a div upon clicking

I am attempting to add a class to a div element when it is clicked. Unfortunately, I'm having trouble getting it to work despite setting it up in the following manner: Javascript: function choose() { this.addClass("selected"); } HTML: <div ...

What is the best way to transform React API data into props that can be utilized in different components?

I've been struggling with this issue for quite some time now, unable to understand how to manipulate the data in a way that allows me to use it in other components. Although I can display the data correctly, I'm advised to structure it within a f ...

AngularJS Date Selection with UI Bootstrap Tool

Just starting out with AngularJS and looking to add a datepicker to my project. I'm using angular.min.js version AngularJS v1.5.0-rc.1 ui-bootstrap-tpls-0.12.0.js version 0.12.0. There are so many examples online that it's confusing. How do I go ...

When transitioning from another page, the header will cover a portion of the section

I am facing a specific issue that I need help with. My goal is to have the navigation bar link to different sections of a single page when clicked. For example, clicking on "Contact" should take the user to the contact section, and then if they click on "A ...

Swapping out bullet points for delicious food icons in an unordered list on an HTML page

I am working with the following code snippet: <div id="instructions"> <h3>Get it done</h3> <ol> <li>In a blender add the eggs, chocolate powder, butter, flour, sugar and milk.</li> <li>Then whisk ...

Can media queries styles be applied to a window of random size using JavaScript?

Can JavaScript be used to apply media queries style based on random window sizes? I have 5 buttons that I want to switch styles for using JavaScript according to the media queries defined in my CSS stylesheet. Is there a method to achieve this? ...

Navigating through the API routes in Express

Within my node API, I have set up two middlewares: app.use('/api', apiRouter); app.use('/*', express.static('public')); The first middleware serves the API endpoints (e.g. /api/users - which returns all users without ent ...

Encountered difficulty parsing json data using cUrl in a PHP script

This is my first time encountering a web service. The JSON data from the .NET server is received and encoded to base64 by the PHP server. The issue I am facing currently is the inability to access each attribute within the data: Array ( [JSONDataResult] ...