admin管理员组文章数量:1353605
In JavaScript
script I have created following dictionary.
var dictionary =[];
$(function () {
dictionary.push({
key: @item.Key.ToShortDateString().ToString(),
value: @Html.Raw(JsonConvert.SerializeObject(item.Value)),
});
alert(dictionary['2017-09-19']);
});
In alert it shows me undefined
. How can I read value from this dictionary?
In JavaScript
script I have created following dictionary.
var dictionary =[];
$(function () {
dictionary.push({
key: @item.Key.ToShortDateString().ToString(),
value: @Html.Raw(JsonConvert.SerializeObject(item.Value)),
});
alert(dictionary['2017-09-19']);
});
In alert it shows me undefined
. How can I read value from this dictionary?
- date 2017-09-19 is added eariler as a key. – maciejka Commented Sep 10, 2017 at 17:18
- 1 You have an array, it's not a dictionary, and it doesn't have named keys, but indexes. Your array contains objects though. It seems you wanted an object instead of the array – adeneo Commented Sep 10, 2017 at 17:19
- It also turned out that key must be saved using @Html.Raw(JsonConvert.SerializeObject to read value by key as a date saved in string. – maciejka Commented Sep 10, 2017 at 18:23
2 Answers
Reset to default 4Rather than using an array use an object
$(function () {
var dictionary = {};
dictionary[@item.Key.ToShortDateString().ToString()] = @Html.Raw(JsonConvert.SerializeObject(item.Value));
alert(dictionary['2017-09-19']);
});
The variable dictionary is an array which consists of objects. If you want to access you need to access by index.
DEMO
var dictionary = [];
dictionary.push({
key: '2017-09-19',
value: 'test',
});
var result = dictionary.filter(function(element) {
return element.key == '2017-09-19';
});
if (result.length > 0) {
// we have found a corresponding element
console.log(result[0].value);
}
本文标签: jqueryGet value from dictionary in JavaScript by keyStack Overflow
版权声明:本文标题:jquery - Get value from dictionary in JavaScript by key - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743862782a2552049.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论