Vald
Vald

Reputation: 237

Add a key/value pair to a specific Javascript object

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 are you from?";
var newAnswer = "I'm from Australia";

If I want to add my new question/answer to my data with a specific id, I can do :

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

But what if I want to add the question and the answer separately? (for example to execute code in the meantime)

I've tried the following but none of them 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;

Upvotes: 0

Views: 49

Answers (2)

Narendra Chouhan
Narendra Chouhan

Reputation: 2319

You can this way, mistake was that you must first bind the "6773" object

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]={}  // mistake was here you first bind the "6773" object 
data[6763]['Question'] = newQuestion;
data[6763]['Answer'] = newAnswer;

console.log(data)

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28424

You have to initialize date[6763] first:

var data = {
     "2738": {
          "Question": "How are you?",
          "Answer": "I'm fine"
      },
      "4293": {
           "Question": "What's your name?",
            "Answer": "My name is John"
      }
};
var newQuestion = "1", newAnswer = "2";
data[6763] = {};
data[6763].Question = newQuestion;
data[6763].Answer = newAnswer;
console.log(data);

Upvotes: 1

Related Questions