Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  199] [ 3]  / answers: 1 / hits: 21953  / 10 Years ago, wed, march 5, 2014, 12:00:00

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?


More From » arrays

 Answers
1

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;

[#72143] Tuesday, March 4, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makiyac

Total Points: 470
Total Questions: 100
Total Answers: 115

Location: Botswana
Member since Sat, Jan 7, 2023
1 Year ago
makiyac questions
Sun, Jan 16, 22, 00:00, 2 Years ago
Thu, Dec 17, 20, 00:00, 4 Years ago
Fri, Dec 4, 20, 00:00, 4 Years ago
;