javascript Lodash 在数组中按开始搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31757642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:19:40  来源:igfitidea点击:

Lodash search by startswith in an array

javascriptarrayssearchlodash

提问by Joey Hipolito

I'm creating a simple search that searches an array of objects that starts with a string passed from an input.

我正在创建一个简单的搜索,它搜索以从输入传递的字符串开头的对象数组。

So I have this:

所以我有这个:

var items = [
    {id: 1, tags: ['foo']},
    {id: 2, tags: ['fish', 'ball']},
    {id: 3, tags: ['bar', 'goo']},
];

input.on(function(e) {
    var test = _.filter(items, function(item) {
         return _.includes(_.pluck(items, 'tags'), input.val());
    });
    console.log(test);
});

This always returns an empty array, I think i'm missing startsWith, how do I use it here in my implementation:

这总是返回一个空数组,我想我错过了startsWith,我如何在我的实现中使用它:

The expected output should be:

预期的输出应该是:

input: 'f'
output: [{id: 1, tags: ['foo']}, {id: 2, tags: ['fish', 'ball']}]

since the two items have tags that starts with f

因为这两个项目的标签以 f

回答by Alex Netkachov

Basically, you do not need lodash for that:

基本上,您不需要 lodash:

var test = items.filter(function (item) {
  return item.tags.some(function (tag) {
    return 0 === tag.indexOf(input.val());
  });
});

But if you like, you can use it

但是如果你喜欢,你可以使用它

var test = _.filter(items, function (item) {
  return _.some(item.tags, function (tag) {
    return _.startsWith(tag, input.val());
  });
});

回答by num8er

Try this:

试试这个:

$(function(){
var items = [
    {id: 1, tags: ['foo']},
    {id: 2, tags: ['fish', 'ball']},
    {id: 3, tags: ['bar', 'goo']},
];

var input = $('input:first');
input.on('input', function(e) {
    var test = _.filter(items, function(item) {
         for(var t in item.tags) {
           if(item.tags[t].indexOf(input.val())==0) {
             return true;
           }
         }
  
         return false;
    });
    console.log(test);
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/lodash/lodash/3.10.0/lodash.min.js"></script>

<input>

回答by dynamitereed

Try this:

试试这个:

var items = [
    {id: 1, tags: ['foo']},
    {id: 2, tags: ['fish', 'ball']},
    {id: 3, tags: ['bar', 'goo']}
];

input.on(function(e) {
    var test = _.filter(items, function(item) {
        return _.chain(items.tags)
                .map(_.partial(_.startsWith, _, input.val()))
                .any()
                .value();
    });
    console.log(test);
});