KnockoutJS - Databind to a dictionary collection

2020-02-09 08:48发布

问题:

How do I use KnockoutJS to bind a dictionary collection to a select list.

If my "Destinations" dictionary looks like this in JSON:

{"Europe":"Europe incl Egypt, Turkey & Tunisia","ANZO":"Australia & New Zealand","WorldwideUSA":"Worldwide (incl USA & Canada)"}

How do I bind this to a select list. Something like this:

data_bind="value: Destination, options: Destinations.Value, optionsText: Destinations.Key"

回答1:

Typically, when dealing with a dictionary, you will want to map it to an array containing objects with key/value properties.

Would be something like:

function mapDictionaryToArray(dictionary) {
    var result = [];
    for (var key in dictionary) {
        if (dictionary.hasOwnProperty(key)) {
            result.push({ key: key, value: dictionary[key] }); 
        }  
    }

    return result;
}

Sample here: http://jsfiddle.net/rniemeyer/7yDTJ/



回答2:

I know this has already been answered but I thought I'd share a more comprehensive solution.

https://github.com/jamesfoster/knockout.observableDictionary

here's a jsfiddle which demos it

http://jsfiddle.net/HLnGs/

hopefully someone else will find this useful



回答3:

A simpler option if you're creating the server API is to just convert the dictionary to an array on the server and return the array:

Dictionary<string, string> myDict = ... ;
return myDict.toArray();  // returns KeyValuePair<string, string>[]

Now you can easily bind the array in knockout ...

<select class="form-control" 
  data-bind="options: opts, optionsText: 'Value', optionsValue: 'Key', optionsCaption: 'Show All', value: filter.myVal">
</select>


标签: knockout.js