1

Is it possible for the Knockout.js Mapping plugin to access json nested data or can it only find the first level data?

If the mapping plugin cannot access nested data is there another solution?

In my example, "Number" is mapping correctly but "DueDate" will not map.

// json with nested data
{
   "Level1":[
      {
         "Level2":{
            "DueDate":"\/Date(1362124800000)\/",
            },
         "Number":5499
      },
}

// Here's my data model - I need to map the "DueDate" observable.
var viewModel;
$.getJSON('/myJsonData', function (data) {
    viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
});

2 Answers 2

1

Are you sure that you can't access to DueDate ? Because in my fiddle I can.

// json nested data
var data = {
    "Level1": [{
        "Level2": {
            "DueDate": "\/Date(1362124800000)\/",
        },
            "Number": 5499
    }]
};
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);

var dueDate = viewModel.Level1()[0].Level2.DueDate;

alert(typeof dueDate);
Sign up to request clarification or add additional context in comments.

Comments

1

I used home grown one way recursive mapping function. It has worked well for me and it's tiny.

function convertToObservable(obj) {
    var newObj = {},
        key,
        value;

    if (!$.isPlainObject(obj)) {
        return obj;
    }

    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            value = obj[key];
            // console.log(key + ':', value);
            newObj[key] = $.isArray(value)
                ? ko.observableArray($.map(value, convertToObservable))
                : $.isPlainObject(value) ? convertToObservable(value) : ko.observable(value);
        }
    }
    return newObj;
}

It has dependency to jQuery, but can be rewritten if don't use jQuery.

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.