3

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?

2
  • 2
    Though the console displays [], a does contain all the items. Just change var a = []; to var a = {}; Commented Mar 5, 2014 at 7:23
  • 1
    JSON Arrays don't support named keys; just numbered indices. So, they can't be included in the string. You can however use named keys with Objects -- var a = {};. Commented Mar 5, 2014 at 7:23

1 Answer 1

9

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.