Sandeep sandy Sandeep sandy - 10 months ago 70
Javascript Question

How frame Json object dynamically with dynamic key and value strings

i have a json
i want to add key value pairs (after framing the below format) like

var json = {};
var a = '"key1" : "value1"'; //coming as dynamic
var b = '"key2" : "value2"'; // coming as dynamic
json.push(a); // i know it is wrong.
json.push(b); // i know it is wrong.
console.log(json); // {"key1": "value1", "key2": "value2"} expected

var array = [];
var c = '{"key1": "value1"}';
var d = '{"key2": "value2"}';
console.log(array); // ["{"key1": "value1"}", "{"key2": "value2"}"]

like the above i can push objects to array, but how can i push json strings directly to a json object.

Answer Source

Firstly a little clarification; there's no such thing as a 'JSON object'. There is a JSON-formatted string, and there is an object. They are two separate entities.

To add strings to an object, specify the property of the object and set its value. You don't need push() for this as that is used exclusively for arrays. In your case, it should look like this:

var obj = {};
obj.key1 = "value1";
obj.key2 = "value2";
console.log(obj); // = { "key1": "value1", "key2": "value2" }

To set a key dynamically use bracket notation:

var key = 'foo';
obj[key] = 'bar';
console.log(obj); // = { 'foo': 'bar' }

If you need to then convert the object to a JSON string, call JSON.stringify on that object:

var json = JSON.stringify(obj);

Also note that in your second example you end up with an array of strings, not an array of objects. If you want an array of objects you need to remove the quotes around the values you set, like this:

var array = [];
var c = { "key1": "value1" };
var d = { "key2": "value2" };
console.log(array); // [{ "key1": "value1" }, { "key2": "value2" }] 

Note the difference in the position of the quotes in the objects and the result from the console.