Vijay Kumar Vijay Kumar - 3 months ago 15
AngularJS Question

how to convert array with index value into json in angular js

what is the best way to convert this array in to json in angular js:

here i need to convert this data into json

0:"1800-300-1947"
1:"112"
2:"8529631485"
3:"7299490148"


i have tried
var myJsonString =JSON.stringify(data);


but its not working it shows like '[]' in the log

In this code i am getting the value from array and pushed into the another array called
data
. if i log the data i got the above result. how to convert that into json

here i have added my code for your reference

var data = Array();
for (var i = 0; i < contacts.length; i++) {
var contact = contacts[i].phoneNumbers[j].value;
console.log(contact);
data.push(contact);
}
var myJsonString =JSON.stringify(data);
console.log(myJsonString);

Answer

Please refer below code for reference its working.

            var contacts = [];
            contacts[0] = {"phoneNumbers": ["1800-300-1947"]};
            contacts[1] = {"phoneNumbers": ["112"]};
            contacts[2] = {"phoneNumbers": ["8529631485"]};
            contacts[3] = {"phoneNumbers": ["7299490148"]};  
            var myJsonString = JSON.stringify(contacts);
            console.log(myJsonString);

Comments