繁体   English   中英

jQuery-每个JSON键值对数组的值的正则表达式

[英]jQuery - Regex on value of each JSON key-value pair array

假设您有一组JSON键/值对,例如:

var LNsIDs = [
    {2053 : 'Jones'},
    {9862 : 'Roberts'},
    {1567 : 'Collins'},
    {etc}
];

有没有一种方法可以仅引用这些对的值,而不必将其与键无关。 (换句话说,无需循环遍历数组并将值馈送到新数组中。)

我正在为与常规数组一起使用的自动完成功能执行正则表达式。 这部分代码如下所示:

$("#lastname").autocomplete({
    source: function(request, response) {
        var esc = $.ui.autocomplete.escapeRegex(request.term);
        var regex = new RegExp("^" + esc, "i");
        var result = $.grep(LNsIDs, function(item){
            return regex.test(item.label);
        });
        response(result);
    },
    select: ...

这适用于常规数组-例如,如果数组如下:

var LNsIDs = ['Jones', 'Roberts', 'Collins', etc]; 

底线:如何对这些对的值执行此正则表达式,以便可以检索所选对的键?

确切地确定您想要什么有点困难,但这也许会让您走上正确的道路。 似乎主要的困难是LNsIDs数组中的对象没有一致的属性名称,因此您无法轻松地引用它们。 这是一个潜在的解决方案:

 var LNsIDs = [ {2053: 'Jones'}, {9862: 'Roberts'}, {1567: 'Collins'}, ]; var regex = /^R/i; var result = $.grep(LNsIDs, function(item) { // Pull out the name of the first property on our object var key = Object.keys(item)[0]; // Use the key to lookup and test the value of that property if (regex.test(item[key])) { // We match, so add two new properties to the object // before returning true: // // 1. The property name (ie 2053) // 2. The value of that property (ie Jones) item.key = key; item.label = item[key]; return true; } // We don't match so we don't bother setting additional // properties return false; }); // Once we have our result, it will just be an array of matches // and each of the objects in it will have a 'key' and a 'label' // property we can look at: for (var i = 0; i < result.length; i++) { alert('Found match with key ' + result[i].key + ' and label ' + result[i].label); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

我最终能够通过“正确”的方式实现此目标,也就是说,通过在源中放置两个单独的AJAX调用并选择自动完成功能的参数,然后从我的数据源中输出传统的JSON数组来实现此目标。 显然,这一直是执行此操作的正确方法。 谢谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM