0

lets say there is customer object, i need to add new element address to this json object customer. how can I achieve this?

Both of these are not altering the customer JSON object

customer['address'] = addressObj 

customer.address = addressObj

and I can not use push() as this is not adding a new item in list of objects.

Thanks, Naren

Misha Huziuk
  • 170
  • 4
  • 18
Naren Karanam
  • 61
  • 1
  • 3
  • 10

2 Answers2

0

Maybe your addressObj is not properly formed.

This works for me:

var customer = {"name": "Naren"};
customer.address1 = "stackoverflow";
customer.address2 = {"fulladdress":"stackoverflow"};
JSON.stringify(customer)

Output:

"{"name":"Naren","address1":"stackoverflow","address2":{"fulladdress":"stackoverflow"}}"
vishwarajanand
  • 1,021
  • 13
  • 23
0

Maybe I am not clear on what exactly you want to do but it sounds to me as if you want have a JSON and want to merge it with another JSON, creating just a JSON file.

 let Json1 = {'Superman': 'Favorite' };
 let Json2 = {'Supergirl': 'Greatest'};
 let Json3 = {'IronFist': 'Top 10' };

You now want to add Supergirl (the new element) to Superman (the old element) I assume. Take a look here @ merge-json a simple package which does its job well. You would code as follows:

use strict;
var mergeJSON = require("merge-json");
let Json1 = {'Superman': 'Favorite' };
let Json2 = {'Supergirl': 'Greatest'};
let Json3 = {'IronFist': 'Top 10' };
let Json6 = mergeJSON(Json1,Json2);
Json6=mergeJSON(Json6,Json3);

You would end up with as follows:

Json6 = {'Superman': 'Favorite', 'Supergirl': 'Greatest', 'IronFist': 'Top 10'}

This is how I make use of combining JSON information or text information into a JSON file. You can get much more sophisticated with the module mentioned above. (Just do not confuse merge-json with json-merge and other modules.)

If this is not what you are looking for my apologies, then I did not understand the question correctly.

twg
  • 1,075
  • 7
  • 11