如何从c#字典创建动态javascript对象

时间:2018-03-01 18:12:47

标签: javascript c#

我的数据结构如下:

public class Entity
{
        public string Key { get; set; }
        public string Value { get; set; }
        public string Category { get; set; }

}

 public class MYNModel : PageModel
 {
        public Dictionary<string, Dictionary<string, string>> Dictionary { get; set; }

        public void OnGet()
        {
            var entityList = new List<Entity>();

            entityList.Add(new Entity() { Category = "Fr", Key = "Yes", Value = "Oui" });
            entityList.Add(new Entity() { Category = "Fr", Key = "No", Value = "Non" });
            entityList.Add(new Entity() { Category = "Fr", Key = "One", Value = "Une" });

            entityList.Add(new Entity() { Category = "En", Key = "Yes", Value = "yes" });
            entityList.Add(new Entity() { Category = "En", Key = "No", Value = "no" });
            entityList.Add(new Entity() { Category = "En", Key = "One", Value = "one" });


            Dictionary = new Dictionary<string, Dictionary<string, string>>();
            Dictionary = entityList
                       .GroupBy(x => x.Category)
                       .Select(x => new KeyValuePair<string, Dictionary<string, string>>(x.Key, x.ToList().ToDictionary(y => y.Key, y => y.Value)))
                       .ToList().ToDictionary(x => x.Key, x => x.Value);

        }
}

所以在javascript部分我可以解析字典:

 var dictionary = JSON.parse('@Html.Raw(Json.Serialize(Model.Dictionary))');

结果是这样的:

{"Fr":{"Yes":"Oui","No":"Non","One":"Une"},"En":{"Yes":"yes","No":"no","One":"one"}}

现在,我可以通过名称搜索来访问我的对象:

var yesValue = dictionary["Fr"]["Yes"];

但目标是创建一种动态javascript对象来访问它:

dictionary.Fr.Yes

我怎样才能在javascript中创建动态对象来访问这样的值?任何想法?

更新

正如Mateusz Kleinert所述,它已经可以使用相同的对象:Property accessor

所以不再有问题了。

0 个答案:

没有答案