Adding a new key-value pair to a JSON data structure

Here is the JSON object that I am currently handling:

{
    "name": "John Smith",
    "age": 32,
    "employed": true,
    "address": {
        "street": "701 First Ave.",
        "city": "Sunnyvale, CA 95125",
        "country": "United States"
    },
    "children": [
        {
            "name": "Richard",
            "age": 7
        },
        {
            "name": "Susan",
            "age": 4
        },
        {
            "name": "James",
            "age": 3
        }
    ]
}

Now, I aim to include a new key-value pair like this:

"collegeId": {
                      "eventno": "6062",
                      "eventdesc": "abc"
                                            }; 

I attempted to combine them using concat but it resulted in || symbol and I couldn't iterate. Splitting only removes commas.

concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));

Can you guide me on how to add a new key-value pair to an existing JSON object in JavaScript?

Answer №1

This method has proven to be the most straightforward and effective for me.

var data = {
        "name": "John Smith",
        "age": 32,
        "employed": true,
        "address": {
            "street": "701 First Ave.",
            "city": "Sunnyvale, CA 95125",
            "country": "United States"
        },
        "children": [
            {
                "name": "Richard",
                "age": 7
            },
            {
                "name": "Susan",
                "age": 4
            },
            {
                "name": "James",
                "age": 3
            }
        ]
    };
    data.schoolId = {"eventno": "6062","eventdesc": "abc"};

Answer №2

To begin, create an object with the reference "collegeId", and then add two additional key-value pairs to that object:

var concattedjson = JSON.parse(json1);
concattedjson["collegeId"] = {};
concattedjson["collegeId"]["eventno"] = "6062";
concattedjson["collegeId"]["eventdesc"] = "abc";

If your data is in string format, you must first parse it before extending it.

Edit

Check out this demo for those who are skeptical about its functionality.

Answer №3

To transform the JSON string into an object, utilize JSON.parse() and proceed to append the property. If you require it in string form again, use JSON.stringify().

By the way, a JSON object does not exist. There are objects and JSON strings that portray those objects.

Answer №4

let updatedJson = JSON.parse(JSON.stringify(originalJson));
updatedJson.schoolId = {"eventno": "3456","eventdesc": "xyz"};
originalJson = updatedJson;

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

The React.js component search test encounters errors in locating components

I have been working on a React app that utilizes Redux and React-router. I am currently writing tests using React TestUtils, and I encountered an issue with the following test results: The first expect statement is successful: expect(nav).to.have.length(1) ...

The Material-UI selector isn't functioning properly for me

I recently tried to incorporate a material-ui selector example into my project by referring to the code fragment obtained from an example on Github. import React from "react"; import {withStyles} from "material-ui/styles"; import Select from "material-ui/ ...

An error occurred in Objective-C, as an unrecognized selector was sent to an instance of `__NSArrayM` when

I am facing difficulties inserting Json data into an SQLite database. The data retrieved from another class is stored in a dictionary (response.item), but I encounter an error stating 'unrecognized selector sent to instance' when trying to insert ...

Incorporate the variables specified in the parent PHP file into the PHP code being received through

I am currently working on a project that involves enabling a user to view his profile upon login. However, I am aiming to have the dashboard load all other profile pages through ajax, such as the view profile and edit profile pages. My progress so far inc ...

Iterate through a local storage object using JavaScript's looping mechanism

I am currently working on a project to create a shopping cart using local storage. I have initialized the local storage with the following code: var cart = {}; cart.products = []; localStorage.setItem('cart', JSON.stringify(cart)); I then use ...

The correct method for including a CSS file in a Vue.js application

How can external CSS files be properly added in a Vue.js Application? I have come across multiple methods for adding CSS files in a Vue.js Application. One suggestion is to use the following code: <link rel="stylesheet" type="text/css" href="/static/b ...

The Naming Convention for NPM Scripts

In my package.json, I have a script that looks similar to this: { ... scripts: { ... "testdb:e2e": "TESTDB_ENV='...' gulp mocha:e2e:backend && gulp mocha:e2e:frontend" } ... } I am interested in adding a s ...

Automatically forward to m.example.com on mobile devices using nodejs

Is there a way to create a subdomain in Node.js, such as m.example.com, and have it redirect to m.example.com on mobile devices? I've searched for answers but haven't found a satisfactory solution. One suggestion is to use nginx in front of Node, ...

Unable to retrieve observable modifications

In my code file for handling reports, named report.service.ts, I have a method that retrieves reports data. This method simply returns a constant array of report objects from a mock source. Here is the implementation: @Injectable() export class ReportServ ...

Vue's innate lifecycle hook

I am looking for a way to automatically run a specific function as a beforeMount hook in every component of my Vue project without having to declare it individually. Essentially, I want a default behavior where if the hook is not explicitly stated in a com ...

Retrieve the <style> tag response and inject it into the head section of the HTML using React

Although I am aware that this may not be the best practice, it seems to be the most suitable solution for this particular case. The server response contains something like this: <style id="styles">.color_txt{color:green;}</style> I am attempt ...

Generate a fresh array of elements and combine the objects that share the same value

Looking to create a new array of objects based on the original specs array of objects. I have searched for similar questions but nothing has solved my issue. const specs = [ { label: 'Brand', value: 'Nike' }, { label: 'Age ra ...

What are the steps for incorporating a YouTube playlist into a website?

I'm in the process of creating a website and I'd like to incorporate a YouTube video playlist that looks similar to this example - http://www.youtube.com/user/icicibank/home. I plan to use HTML5, JavaScript, and the YouTube API. Can you provide g ...

Stop the parent script from executing

I recently encountered an issue with my DotNetNuke website. Embedded within the DNN code is a script that triggers a function called WebForm_OnSubmit(). However, I noticed that this function is also being triggered when I try to perform a search on a speci ...

Transferring String data between Java and JavaScript using Webview in both directions

I'm currently developing an application that allows two users to communicate via a webview. My goal is to transfer a String variable from JavaScript to Java in order to store it in my SQLite database, and also be able to do the reverse operation as we ...

Display or conceal a div depending on the selected radio button

I am attempting to display a hidden div based on the input of a radio button. If the "yes" option is checked, the hidden div should be shown. Conversely, if the "no" option is checked, the div should be hidden. I'm not sure why this code isn't w ...

Pause for a moment before commencing a fresh loop in the FOR loop in JavaScript

Behold, I present to you what I have: CODE In a moment of curiosity, I embarked on creating a script that rearranges numbers in an array in every conceivable way. The initial method I am working with is the "Selection mode", where the lowest value in th ...

What is the best way to create a React filter utilizing the Autocomplete component from MaterialUI and incorporating state management?

I am currently in the process of creating a filter using the Autocomplete component from MaterialUI. As I select options from the dropdown menu, several things are happening: The Autocomplete automatically adds the selected options to the Chip Array. The ...

Angular-UI keypress event allows users to interact with components and

I am facing challenges while using the keypress feature in the following code snippet- <div ng-controller="GBNController"> ... <input id="search-field" type="text" placeholder="JSON Query" ng-model="queryText" ui-keypress="{enter: foo()}"/> .. ...

The Javascript function call from the <img src="myFunction()"> is malfunctioning

I am looking to dynamically pass the URL of an image using a JavaScript function. <head> <script> function myFunction() { var str1 = "somepictureurl.png"; return str1; } </script> </head> <body> <img src="myFu ...