0

All,

I have the following code:

$.ajax({
    url: '@Url.Action("GetMerchantUsers", "Merchant")',
    dataType: 'json',
    success: function (json) {
        var mappedTasks = $.map(JSON.parse(json), function (item) { return new Task(item) });
        self.tasks(mappedTasks);
    }
});

This calls an MVC controller that returns a list of objects from a JsonResult method. It works totally fine. However, I need to rewrite this method because there will never be more than one Task being returned from the server. When I return one task from the server, however, the .NET JsonResult method doesn't put '[' and ']' at the beginning and end of the json, so $.map() sees the PROPERTIES of the object as a collection, but I just want to map one object returned from the server to a task observable instead of multiple tasks to a tasks observable. I'm new to knockout...how do I map a single Json object, like i'm doing above for a collection. I'll be happy to provide more info if needed!

Also, I've already mapped the object to a generic JavaScript type, but I want to map it to my Task type specifically.

3
  • var parsed = JSON.parse(json); parsed = typeof parsed == "array" ? parsed : [parsed]; Commented Sep 10, 2014 at 19:44
  • Chris, this parses to a generic Object. I want an object of type Task. Commented Sep 10, 2014 at 19:46
  • Hit enter too soon. Basically, test if it's an array, if not, add it to an empty array then call your map Commented Sep 10, 2014 at 19:47

1 Answer 1

2

Since you're no longer processing a list, you don't need $.map() (since it just loops through and applies a function to every item in a list), you can just pass the parsed JSON reponse to your Task constructor...like so perhaps:

var mappedTasks = new Task(JSON.parse(json));

If your self.tasks() method expects a list, you can just wrap it:

self.tasks([mappedTasks]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.