user1405195
user1405195

Reputation: 1681

Splitting JSON string into observable array

The below fiddle should shows lists of items.

However, the lists are in string format and haven't yet been split. I've tried to split them without success.

One thing I tried was to split the string to an observable array within the map function. Is this the right approach?

self.splitValues = ko.observableArray();

var mappedItemLists = $.map(data, function(i) {
    return new ItemList(i.title, self.splitValues(i.item.split(" ")))
});

http://jsfiddle.net/bGsRH/428/

Matt's answer accepted.

Upvotes: 1

Views: 1267

Answers (1)

Matt Burland
Matt Burland

Reputation: 45135

Not entirely clear what you actually wanted to do here. Is this what you where looking for:

http://jsfiddle.net/bGsRH/429/

I did this to split your values:

        var mappedTasks = $.map(data, function(item) {
            return new ItemList({ 
                title: item.title,
                items: item.items.split(" ")
            });
        });

(Note: you could have also just changed the ItemList function to take two arguments)

And then in your binding, you need to foreach bindings:

<ul data-bind="foreach: itemlists, visible: itemlists().length > 0">
    <li><span data-bind="text: title"></span>
        <ul data-bind="foreach: items">
            <li data-bind="text: $data"></li>
        </ul>
    </li>
</ul>

If you want the nested list to display as a list.

Upvotes: 2

Related Questions