Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用like查询对对象的筛选器数组加下划线_Javascript_Underscore.js - Fatal编程技术网

Javascript 使用like查询对对象的筛选器数组加下划线

Javascript 使用like查询对对象的筛选器数组加下划线,javascript,underscore.js,Javascript,Underscore.js,我有下面的Json { "results": [ { "id": "123", "name": "Some Name" }, { "id": "124", "name": "My Name" }, { "id": "125", "name": "Johnson Johnson" }, { "id": "126", "name": "Mike

我有下面的Json

{
  "results": [
    {
      "id": "123",
      "name": "Some Name"
    },
    {
      "id": "124",
      "name": "My Name"
    },
    {
      "id": "125",
      "name": "Johnson Johnson"
    },
    {
      "id": "126",
      "name": "Mike and Mike"
    },
    {
      "id": "201",
      "name": "abc xyz"
    },
    {
      "id": "202",
      "name": "abc befd"
    },
    {
      "id": "210",
      "name": "jki yuiu"
    },
    {
      "id": "203",
      "name": "asdfui uiuu"
    },
    {
      "id": "204",
      "name": "sfdhu uiu"
    },
    {
      "id": "205",
      "name": "asdfui uyu"
    }
  ]
}
使用下划线,我想使用类似sql的id查询来过滤上述数据。 例如,如果通过2,则应过滤json并返回一个新json,其中包含以2开头的id,如果通过20,则应返回id以20开头的新json

类似于类sql查询,然后返回n个匹配结果


更正:我想要以id 2或我传递的任何参数开头的数据我需要以它开头的数据

关于Array.prototype.filter和Array.prototype.slice呢?下划线具有类似的函数,但如果可以用纯JS解决,为什么还要使用它们呢

function sqlLikeFilter(data, id, maxn) {
    return data.result.filter(function(x) { return x.id == id; }).slice(0, maxn);
}

console.log(sqlLikeFilter(yourData, 125, 1));
试试这个

function(id){
    var result = _.filter(results, function(value) {
        return value.id === id
    })
    return result;
}
试试这个

function getResult(keyToFilter, valueStartsWith){
    return _.filter(results, function(d){ return d[keyToFilter].startsWith(valueStartsWith); })
}

getResult("name", "asdfui");

[{
  "id": "203",
  "name": "asdfui uiuu"
},
{
  "id": "205",
  "name": "asdfui uyu"
}]

arr.filterobj=>obj.id.indexOf2try@Tushar是正确的。Lodash/下划线中还有一个u.filter方法。如果你在问这个问题之前费心去谷歌,你就会知道,Array.prototype.filter是“filter javascript Array”的最高结果@user804401签出我的更新答案。更正:我想要以id 2开头的数据或我传递的任何参数,我需要以id 2开头的数据。我想下划线会有帮助的