簡體   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