1

How to add

{date: 11 Nov 2013 }

to

{ question: { title: 'a', body: 'b' }, tags: [ { name: 'Civil Laws' } ] }

so that it looks like :-

{ 
 question: { title: 'a', body: 'b' }, 
 tags: [ { name: 'Civil Laws' } ], date: 11 Nov 2013 
}

in javascript.

Sangram Singh
  • 7,161
  • 15
  • 50
  • 79

3 Answers3

1

Presumably your

{ question: { title: 'a', body: 'b' }, tags: [ { name: 'Civil Laws' } ] }

is actually assigned to a variable, like

myObject = { question: { title: 'a', body: 'b' }, tags: [ { name: 'Civil Laws' } ] }

So just use

myObject.date = new Date()

or

myObject["date"] = new Date(2013, 11 - 1, 13)

or

myObject.date = "13 Nov 2013"

Or any combination of those, depending on what exactly you're after...

If you're asking about how best to serialize dates into JSON, that is a different issue discussed here (and everywhere else when Googling for JSON dates)

Update: after reading dooxe's answer, I realise that you were probably asking about combining two objects into one. In which case dooxe's answer is probably what you want

Community
  • 1
  • 1
Shai
  • 7,159
  • 3
  • 19
  • 22
1

You can do it like this :

http://jsfiddle.net/Sn9zD/1/

Javascript:

function extend(o1, o2)
{
   for(var p in o2)
   {
      o1[p] = o2[p];
   }
   return o1;
}

Then :

var d = {date: new Date() };
var o = { 
 question: { title: 'a', body: 'b' }, 
 tags: [ { name: 'Civil Laws' } ]
};
o = extend(o, d);

If you use jQuery, you have jQuery.extend.

dooxe
  • 1,481
  • 12
  • 17
0

The problem becomes simple when u realize x = { question: { title: 'a', body: 'b' }, tags: [ { name: 'Civil Laws' } ] }; is actually a javascript object.

hence: x.date = new Date(); would do it

Sangram Singh
  • 7,161
  • 15
  • 50
  • 79