简体   繁体   English

如何将对象添加到Javascript对象中?

[英]How can I add an object to an object in Javascript?

I have the following javascript object that came back from an Entity Framework 5 get from a SQL Server database. 我有一个从SQL Server数据库获取的Entity Framework 5返回的以下javascript对象。

var a =
 {
  "questionId":14,
  "questionStatusId":1,
  "answers":null
 }

var b =
 {
  "questionId":15,
  "questionStatusId":1,
  "answers":[
   {"answerId":34,"correct":true,"response":false,"text":"5","image":null,"questionId":15},
   {"answerId":35,"correct":false,"response":false,"text":"50","image":null,"questionId":15}]
 }

I would like to add an empty answer object and then send back to the server with a PUT. 我想添加一个空的答案对象,然后使用PUT发送回服务器。

How can I add an answer object to variable a and to variable b ? 如何将答案对象添加到变量a和变量b中?

var answer=[];
a.push( { "answer":answer } );
b.push( { "answer":answer } );

Something like 就像是

var newAnswer = {"answerId":0,"correct":false,"response":false,"text":"","image":null,"questionId":0};
b.answers.push(newAnswer);

is probably what you are looking for. 可能正是您想要的。

You can add properties o objects at runtime in JavaScript. 您可以在运行时使用JavaScript在对象中添加属性。 For example 例如

var a = { f : 10, g : 20 };
a.h = 30; 

Similarly, just add the answers property to your a & b with blank objects. 同样,只需将答案属性添加到带有空白对象的a&b中。

a.answer = []; // Empty non null array
b.answer = []; // "

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

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