例如,我有这样的JavaScript数组:
var data = [
{text:'Business', aid:'6'},
{text:'Careers', aid:'29'},
{text:'Credits', aid:'28'},
{text:'Insurance', aid:'30'}
];
现在,在URl中传递了ID,我需要根据该ID从这个数组中获取“text”,如:
$('#category').val(data, function(item) {return item.aid['6'].text;} ); // = Business
所以我想基于传递的URL ID = aid来填充表单字段#category和数组中的文本?
提前致谢
答案 0 :(得分:1)
使用filter
[MDN] 方法获取正确的对象:
var aid = 28,
match = data.filter(function(elem) { return elem.aid == aid; });
if (match.length) {
$('#category').val(match[0].text);
}