KnockoutJS - 数据绑定到字典集合 [英] KnockoutJS - Databind to a dictionary collection

查看:26
本文介绍了KnockoutJS - 数据绑定到字典集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 KnockoutJS 将字典集合绑定到选择列表.

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

如果我的目的地"字典在 JSON 中是这样的:

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"

推荐答案

通常,在处理字典时,您需要将其映射到包含具有键/值属性的对象的数组.

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

应该是这样的:

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

    return result;
}

示例:http://jsfiddle.net/rniemeyer/7yDTJ/

这篇关于KnockoutJS - 数据绑定到字典集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆