Jaydeep Gondaliya Jaydeep Gondaliya - 4 months ago 8
Javascript Question

issue with brackets in json response

I tried using below code but its not giving expected result. (i.e Curly bracket)

var arr1 =[];
for (var i=0;i<2;i++)
{
arr1.push('date :'+i);
}

console.log(arr1);

try //mystring = arr1.isArray(arr1);
console.log(mystring);


output:

getting : ["date : ", "date :1"]

expected : {"date : ", "date :1"}

Answer

You're getting an array result as expected, which is what your code does. You cannot create an Object Notation from an array.

If you want to get a JSON string, with an array, the result will be the same :

JSON.stringify([1,3]); // Output : "[1,3]"

What (i think) you want achieve, is to create a Javascript object and then convert it to JSON, however you can't give the same index to a property in an object, therefore you should try with the following snippet instead :

var myObj = {};
for (var i=0;i<2;i++)
{
    myObj["date"+i] = i;
}

console.log(myObj);
console.log(JSON.stringify(myObj));
// Which outputs :
// {"date0":0,"date1":1}

Read more about Javascript objects.