Insert a new key/value pair into a designated object in Javascript

var data = {
  "2738": {
      "Question": "How are you?",
      "Answer": "I'm fine"
  },
  "4293": {
      "Question": "What's your name?",
      "Answer": "My name is John"
  }
}
var newQuestion = "Where do you live?";
var newAnswer = "I live in France";

To add a new question and answer separately to the data with a specific id, you can use different methods like:


data[6763] = {
  "Question" : newQuestion,
  "Answer" : newAnswer,
}

If you wish to add the question and answer one by one (for executing code in between), here are some attempts that will not work:


data[6763].Question = newQuestion;
data[6763].Answer = newAnswer;

data[6763] = {"Question" : newQuestion};
data[6763] = {"Answer" : newAnswer};

Object.getOwnPropertyNames(data)[6763].Question = newQuestion;
Object.getOwnPropertyNames(data)[6763].Answer = newAnswer;

Answer №1

Remember to bind the "6773" object first when performing this action:

let data = {
  "2738": {
      "Question": "How are you?",
      "Answer": "I'm fine"
  },
  "4293": {
      "Question": "What's your name?",
      "Answer": "My name is John"
  }
}

let newQuestion = "Where are you from?";
let newAnswer = "I'm from Australia";

data[6763]={}  // remember to bind the "6773" object first here 
data[6763]['Question'] = newQuestion;
data[6763]['Answer'] = newAnswer;

console.log(data)

Answer №2

To start, make sure you initialize date[6763]:

var database = {
     "2738": {
          "Question": "How do you feel?",
          "Answer": "I'm okay"
      },
      "4293": {
           "Question": "What is your name?",
            "Answer": "I go by Mia"
      }
};
var newQuery = "Hello", newSolution = "Hi there";
database[6763] = {};
database[6763].Question = newQuery;
database[6763].Answer = newSolution;
console.log(database);

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

Using Json.NET to Append JObject to existing JArray

Struggling with a seemingly simple piece of code, can't seem to figure it out. JObject obj = new JObject { "Name", "John" }; JArray array = new JArray(); array.Add(obj); // receiving error message: "Can not add Newtonsoft.Json.Linq.JValue to Newtons ...

Steps for adding a JSON object to an unordered list

After receiving data from a web server, I created a JSON object using the code obj = JSON.parse(data). This object contains information about dinosaurs such as their name, group, diet, and period. This is what the JSON object looks like: [{"name":"Stauri ...

Tips for efficiently storing data in the Laravel database using Ajax

I'm attempting to upload a product with multiple images to the database without refreshing the page. Despite not encountering any errors in the console, I am seeing a long block of text that starts like this: <script> Sfdump = window.Sfdump || ...

Using Passport.js with a custom callback function that accepts parameters

I currently have this block of code: app.post('/login', passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), function(req, res) { return res.redirect('/profile/&a ...

VUEJS - Link the output from my function to my sub-template

I am looking for a way to link the output of my function with the child template. methods object methods: { filterOptions(checkedValues: any) { let filtered = this.cards.filter(card => { return card.profile .map(prof ...

Where should I place my custom menu script in Wordpress and how do I do it?

I am currently exploring the realms of PHP, Wordpress, and Javascript as I endeavor to transform my website, crafted with CSS and HTML, into a dynamic theme for Wordpress using PHP. One particular feature on my site is an off-screen menu that smoothly ope ...

Attempting to output properties from an Express/Mongo API by utilizing a React.js frontend

I am currently in the process of developing a simplistic fictional sneaker application with the MERN stack. While I wouldn't classify myself as a beginner, I'm also not an expert. I successfully created the backend and generated a json rest-api. ...

Creating an application for inputting data by utilizing angular material and javascript

I am looking to create an application using Angular Material Design, AngularJS (in HTML), and JavaScript. The application should take input such as name, place, phone number, and email, and once submitted, it should be stored in a table below. You can fin ...

What is the best way to retrieve all string constants from HTML or JSX code?

UPDATE: I recently developed my own babel plugin CLI tool named i18nize-react :D I am currently in the process of translating an existing react application from English to another language. The string constants in the JSX are all hardcoded. Is there a sim ...

It is not feasible to establish a personalized encoding while sending a post request through XMLHTTPRequest

When using the JS console in the latest version of Chrome browser, I encountered the following issue: x = new XMLHttpRequest(); x.open('POST', '?a=2'); x.setRequestHeader('Content-Type', 'application/ ...

`Carousel nested within tabbed interface`

I am currently facing an issue with my website's tabs and carousels. I have 4 tabs, each containing a carousel, but only the carousel in the first tab seems to be working properly. When I activate the second tab, all the carousel divs collapse. For r ...

Building a web proxy with node.js and express

I'm currently in the process of designing a personalized web proxy using JavaScript to allow users to surf the internet through a designated website, similar to this . One challenge I encountered is transferring the response from a URL back to the us ...

Sharing a Twitter thread using Twit library with Node.js

I have been using Node.js along with the npm Twit module to post tweets on Twitter, and while it works for a single tweet, I am facing issues when trying to post multiple tweets as a thread. When attempting to post a series of tweets together, they do not ...

Saving an image and form data together in local storage can be accomplished by using JavaScript

Is there a way to save an image to local storage along with form data? I would like to store the form data in a database and keep the image in local storage. Any help would be greatly appreciated. Thank you! <form id="saveImageForm"><input type ...

Determining button click events in VueJS using the Watch method

Creating a feature for undo/redo in VueJS involves watching the settings and adding a new element to an array of changes when there is a setting change. Additionally, there is a method for undoing actions when the corresponding button is clicked. An issue ...

Automatically trigger the expansion of all panels within Vuetify using code

I'm attempting to use Vuetify 2.3.5 to programmatically control the opening and closing of expansion panels. <v-expansion-panels accordion> <v-expansion-panel v-for="(item,i) in faqs" :key="i"> <div class ...

What are the potential causes of receiving the error message "No Data Received ERR_EMPTY_RESPONSE"?

I often encounter this issue on my website, especially when I have a thread open. It seems to happen whenever I am actively checking for new posts and notifications via Ajax every 10 seconds or so. However, I'm not sure if this continuous reloading is ...

Is it possible to load a JS file without using the require function?

Is there a method to load a JavaScript file without using require, but with fs for instance? I am aware that for JSON files I can utilize: const jsonFile = JSON.parse(fs.readFileSync("/jsonfile.json")) Can the same be done for a JavaScript file? I am inq ...

The tale of Legend remains unchanged

I have created two graphs (Stacked Bar and Line) on a single SVG. Both are being appended properly, but I need legends for both graphs within the same svg. Legends are showing up for the stacked bar graph but not for the line graph. Below is the code: var ...

Utilizing a V-for/V-if loop to iterate through a multi-dimensional array and filter data based on date

I'm facing a challenge with setting up a v-for loop for an array I've constructed, which is already in the desired format Below is a snippet representing the data format. Essentially, I want to create a table for employees where the header consi ...