Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Convert Array to JSON

I have an array containing 3 elements

var a = [];
  a["username"]=$scope.username;
  a["phoneNo"]=$scope.phoneNo;
  a["altPhoneNo"]=$scope.altPhoneNo;

Now, I want to send this data to server in JSON format. Therefore, I used

    var aa = JSON.stringify(a);
    console.log("aa = "+aa);

But the console displays empty array

aa = [] 

How can I convert this array into JSON?

like image 969
Aniket Sinha Avatar asked Mar 20 '26 22:03

Aniket Sinha


1 Answers

That's not the correct way to add elements to an array, you're adding properties instead. If you did console.log(a.username); you'd see your $scope.username value.

You could either do

var a = [];
a.push({"username": $scope.username});
a.push({"phoneNo": $scope.phoneNo});
a.push({"altPhoneNo": $scope.altPhoneNo});

But it looks more like what you're trying to do is

var a = {};
a["username"] = $scope.username;
a["phoneNo"] = $scope.phoneNo;
a["altPhoneNo"] = $scope.altPhoneNo;

That is, you want your a to be an object if you're going to add properties to it. And that would be better written as

var a = {};
a.username = $scope.username;
a.phoneNo = $scope.phoneNo;
a.altPhoneNo = $scope.altPhoneNo;
like image 57
ivarni Avatar answered Mar 23 '26 12:03

ivarni