简体   繁体   中英

Trouble creating object from Json using Knockout

Ok, the scenario is that I have a list of objects that itself contains a list of objects. I am trying to put the outer objects in a list in my View-Model and I'm trying to turn the inner objects into an object I created as a model with an extra property, like so -

function Tag(data, isChecked) {
    var TagId = ko.observable(data.TagId);
    var Description = ko.observable(data.Description);
    var IsActive = ko.observable(data.IsActive);
    var checked = ko.observable(isChecked)
}

Here is how i'm doing it.

   $.each(parentTags, function (i, tag) {
    var tempTag = tag[i];
    for (Object in tag.ChildTags)
    {
        var checked = false;
        for(checkedItem in savedTags)
        {
            if(tag.ChildTags[Object].TagId === savedTags[checkedItem])
            {
                checked = true;
            }
        }
        //var tempChild = new Tag(tag.ChildTags[Object], checked);
        tempTag.ChildTags.push(new Tag(tag.ChildTags[Object], checked));
    }
    viewModel.ModelTags.push(tempTag);
});

parentTags = [[object Object],[object Object],[object Object],[object Object],[object Object],]

I'm definitely new to json and knockout. Any help would be appreciated.

This is what I have now and it seems to be working.

    $.each(parentTags, function (i, tag) {
    var tempTag = new Tags(JSON.parse(JSON.stringify(tag)));
    tempTag.ChildTags().length = 0;

    for (Object in tag.ChildTags) {
        var checked = false;
        for (checkedItem in savedTags) {
            if (tag.ChildTags[Object].TagId === savedTags[checkedItem]) {
                checked = true;
            }
        }

        tempTag.ChildTags().push(new Tag(tag.ChildTags[Object], checked));
    }
    viewModel.ModelTags().push(tempTag);
});

What are you doing with var tempTag = tag[i]; ? The variable tag is already the i-th member of parentTags.

If I understand you correctly, try this:

function Tag(data, isChecked) {
   // not "var TagId", please.
   this.TagId = ko.observable(data.TagId);
   this.Description = ko.observable(data.Description);
   this.IsActive = ko.observable(data.IsActive);
   this.checked = ko.observable(isChecked);
}

$.each(parentTags, function (i, tag) {
    // map each child tag into a Tag object
    var tags = $.map(tag.ChildTags, function(cTag) {
        return new Tag(cTag, $.inArray(cTag.TagId, savedTags));
    });

    // replace with Tag objects
    tag.ChildTags = tags;

    // push modified tag onto vm
    viewModel.ModelTags.push(tag);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM