Miguel Moura
Miguel Moura

Reputation: 39364

Modify JSon format returned by an Ajax request

I have a JQuery plugin where I have the following:

transformResult: function(response, originalQuery) {

}

Inside this function I need to convert the originalQuery Json data:

[
  { "Id": 4, "Title": "Title 4" },
  { "Id": 2, "Title": "Title 2" }
]

Into the response Json data format:

{
  suggestions: [
    { data: "4", value: "Title 4" },
    { data: "2", value: "Title 2" }
  ]
}

Id is the data and Title is the value.

How can I do this?

Thank you, Miguel

Upvotes: 0

Views: 62

Answers (1)

adeneo
adeneo

Reputation: 318182

var arr =[
  { "Id": 4, "Title": "Title 4" },
  { "Id": 2, "Title": "Title 2" }
]

var obj = {suggestions : []};

$.each(arr, function(i, o) {
    obj.suggestions.push({name : o.Id, value : o.Title});
});

FIDDLE

Upvotes: 3

Related Questions