Alan2
Alan2

Reputation: 24602

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.

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.

How can I add an answer object to variable a and to variable b ?

Upvotes: 0

Views: 75

Answers (3)

user2587132
user2587132

Reputation:

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

Upvotes: 2

mohkhan
mohkhan

Reputation: 12335

You can add properties o objects at runtime in 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.answer = []; // Empty non null array
b.answer = []; // "

Upvotes: 1

UweB
UweB

Reputation: 4110

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.

Upvotes: 1

Related Questions