-3

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?

3
  • ["nameList"]:[{"name":"Tom"},{"name":"John"}] is not correct json format Commented Jun 14, 2016 at 7:40
  • what you have tried? I think you want {"nameList":[{"name":"Tom"},{"name":"John"}]} Commented Jun 14, 2016 at 7:40
  • if you want it? {"nameList" : [{"name":"Tom"},{"name":"John"}]} Commented Jun 14, 2016 at 7:41

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

-1

try this:

JSON.stringify((
     {nameList:[
          {name:"Tom"},
          {name:"John"}
     ]}
))

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.