Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new attribute to existing json object in node.js

I have an object like this

==================records=========={ Id: 5114a3c21203e0d811000088,   userId: 'test',   sUserId: test,   userName: 'test',   url: 'test',   Title: 'test' } 

I need to add a new field Name : 'test' to the above record, I tried giving records.Name = name, it didn't work.

Helps please

Thanks, Prats

like image 394
Prats Avatar asked Feb 08 '13 08:02

Prats


People also ask

How do I add data to an existing JSON object?

Use push() method to add JSON object to existing JSON array in JavaScript. Just do it with proper array of objects .

How do I add a key value pair to an existing JSON object?

To add a new key value pair in existing JSON object using JavaScript, we can parse the JSON string with JSON. parse , then add the key-value pairs we want, and then convert the object back to a JSON string with JSON. stringify .

How do I add a property to a node js object?

To add a new property to a Javascript object, define the object name followed by the dot, the name of a new property, an equals sign and the value for the new property.


2 Answers

I am assuming you are trying to add a property to a returned Mongoose Document to reuse it somewhere else. Documents returned by Mongoose are not JSON objects directly, you'll need to convert them to an object to add properties to them. The following should work:

//... record is a mongoose Document var r = record.toObject(); r.Name = 'test'; console.log("Record ",r); 
like image 102
droider Avatar answered Sep 21 '22 16:09

droider


Those finding this problem, OP mentioned in a comment below the original question that the solution for this problem is:

records.set('Name', 'test') 

This adds a new attribute called Name having value test.

like image 36
Haywire Avatar answered Sep 23 '22 16:09

Haywire