繁体   English   中英

将键/值对添加到特定的 Javascript 对象

[英]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";

如果我想使用特定 ID 将我的新问题/答案添加到我的数据中,我可以这样做:

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

但是如果我想分别添加问题和答案怎么办? (例如同时执行代码)

我尝试了以下但没有一个工作:

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;

你可以这样,错误是你必须先绑定“6773”对象

 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)

您必须先初始化date[6763]

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM