Reputation: 237
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
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
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