Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have an array like this:

["Tom","John"]

And I want to convert it to the following json format:

["nameList"]:[{"name":"Tom"},{"name":"John"}]

How to achieve this?

share|improve this question
    
["nameList"]:[{"name":"Tom"},{"name":"John"}] is not correct json format – 이동권 Jun 14 at 7:40
    
what you have tried? I think you want {"nameList":[{"name":"Tom"},{"name":"John"}]} – Pranav C Balan Jun 14 at 7:40
    
if you want it? {"nameList" : [{"name":"Tom"},{"name":"John"}]} – 이동권 Jun 14 at 7:41

You can run a loop on the existing object, specifying the json data for the new AngularJS object as:

var data = ["Tom", "John"];

$scope.angularData = {
  'nameList': []
};

angular.forEach(data, function(v, k) {
  $scope.angularData.nameList.push({
    'name': v
  });
});

Watch the demo.

share|improve this answer

Use Array.prototype.map function to make a new array with objects. Then convert the array to json.

var namesArray = ["tom", john];

var newArray = namesArray.map(function(item){
   return {'name': item}   
})

console.log(JSON.stringify(newArray));
share|improve this answer

try this:

JSON.stringify((
     {nameList:[
          {name:"Tom"},
          {name:"John"}
     ]}
))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.