【问题标题】:Underscore js find item by ID下划线js通过ID查找项目
【发布时间】:2012-10-05 10:36:44
【问题描述】:

我是 Underscore js 的新手,对如何使用它有点困惑。我有一组“目标”,我想通过 ID 找到其中一个。

这是数据:

{"goal":[
    {
        "category" : "education",
        "title" : "Charlie University",
        "description" : "Lorem ipsum dolor sit amet",
        "date" : "01/03/2020",
        "value" : 50000,
        "achievability" : 3,
        "experimental_achievability": 3,
        "suggested": false,
        "accounts": [
            {
                ...
            },
            {
                ...
            }
        ],
        "articles": [
            {
                ...
            },
            {
                ...
            },
            {
                ...
            }
        ],
        "related_goals": [
            {
                ...
            }
        ],
        "id":"1"
    },
    {
        "category" : "family",
        "title" : "Getting married",
        "description" : "Lorem ipsum dolor sit amet",
        "date" : "01/03/2022",
        "value" : 10000,
        "achievability" : 3,
        "experimental_achievability": 2,
        "suggested": true,
        "accounts": [
            {
                ...
            }
        ],
        "articles": [
            {
                ...
            },
            {
                ...
            },
            {
                ...
            }
        ],
        "related_goals": [
            {
                ...
            }
        ],
        "id":"2"
    }
    ...
]}

这就是我正在尝试的,我想获取整个数组/对象,以便获取它的每个字段:

var goalId = 1;
_.each(result.goal, function(item){
    _.find(result.goal, function(i){
         return i = goalId;
    });
});

知道怎么做吗?

【问题讨论】:

标签: javascript underscore.js


【解决方案1】:

更新

现在是 2016 年,我们可能不需要下划线来实现这一目标。使用Array.prototype.find()。如果数组中的元素满足提供的测试函数,则返回数组中的值。否则返回 undefined。

  // Underscore
  var users = [
    { 'user': 'barney',  'age': 36, 'active': true },
    { 'user': 'fred',    'age': 40, 'active': false },
    { 'user': 'pebbles', 'age': 1,  'active': true }
  ]

  _.find(users, function (o) { return o.age < 40; })
  // output: object for 'barney'

  // Native
  var users = [
    { 'user': 'barney',  'age': 36, 'active': true },
    { 'user': 'fred',    'age': 40, 'active': false },
    { 'user': 'pebbles', 'age': 1,  'active': true }
  ]

  users.find(function (o) { return o.age < 40; })
  // output: object for 'barney'

浏览器支持

--------------------------------------------
| Chrome | Firefox | Safari |  IE  | Opera |
|--------|---------|--------|------|-------|
|   45   |    25   |  7.1   | Edge |  32   |
--------------------------------------------

更多关于 MDN 的 polyfill 信息


更新:我发现_.where 总是返回一个数组。 _.findWhere 返回它找到的第一个对象,因此如果您希望返回单个对象,则使用它会更好。


您可以使用_.where 更容易。

如果是这样的话:

var goal  = [

    {
        "category" : "education",
        "title" : "Charlie University",
        "description" : "Lorem ipsum dolor sit amet",
        "date" : "01/03/2020",
        "value" : 50000,
        "achievability" : 3,
        "experimental_achievability": 3,
        "suggested": false,
        "accounts": [],
        "articles": [],
        "related_goals": [],
        "id":"1"
    },
    {
        "category" : "education",
        "title" : "Charlie University",
        "description" : "Lorem ipsum dolor sit amet",
        "date" : "01/03/2020",
        "value" : 50000,
        "achievability" : 3,
        "experimental_achievability": 3,
        "suggested": false,
        "accounts": [],
        "articles": [],
        "related_goals": [],
        "id":"2"
    },
    {
        "category" : "education",
        "title" : "Charlie University",
        "description" : "Lorem ipsum dolor sit amet",
        "date" : "01/03/2020",
        "value" : 50000,
        "achievability" : 3,
        "experimental_achievability": 3,
        "suggested": false,
        "accounts": [],
        "articles": [],
        "related_goals": [],
        "id":"3"
    },
    {
        "category" : "education",
        "title" : "Charlie University",
        "description" : "Lorem ipsum dolor sit amet",
        "date" : "01/03/2020",
        "value" : 50000,
        "achievability" : 3,
        "experimental_achievability": 3,
        "suggested": false,
        "accounts": [],
        "articles": [],
        "related_goals": [],
        "id":"4"
    }
]

你可以使用类似的东西:

var filteredGoal = _.where(goal, {id: "1"});

【讨论】:

  • 是的 - 比我的解决方案更好!
  • 关于 undersocre() 最好的地方是它的文档......我直接前往文档,搜索我需要的东西,如果它在那里,我会找到它。
  • 我也是。我猜我一直在使用相同的功能的坏习惯。但是感谢您指出 _.where() 的用处,我以后会牢记这一点
  • .findWhere 是我需要的更简洁的解决方案。谢谢。
  • 可以下划线_.findWhere处理子属性,比如lodash _.find可以吗? (lodash.com/docs#find) 这样我就可以搜索 chr.age
【解决方案2】:

您正在使用对象数组。因此,您可以使用:_.findWhere(查看列表并返回与所有键值对匹配的第一个值)来获取所有基于的属性在 id 或其他关键属性上。

var some= [
             {Employee:'ved',id:20}, 
             {Employee:"ved",age:25},
             {Employee:"p",age:2}
          ];

var a = _.findWhere(some,{id:20});
console.log('searchResult',a);

要获取索引,您可以使用以下内容:

var b = _.indexOf(some,a);
console.log('index',b);

如果您需要所有用途列表
试试_.where (它查看数组中的每个匹配项,返回一个包含属性中列出的键值对的所有值的数组。)

var some= [ 
            {Employee:"ved",id:20}, 
            {Employee:"ved prakash",id:20},
            {Employee:"anyone",id:2}
          ];
var a = _.where(some,{id:25});
    console.log('searchResult',a);

_.find:只检查value,不检查key-value。


访问文档:_.find

【讨论】:

    【解决方案3】:

    已经简化了您的数据模型,但是像这样?

    var goals = [{id:1, name:'Goal1'},
                 {id:2, name:'Goal2'},
                 {id:3, name:'Goal3'}];
    
    function getGoal(id) {
        return _.find(goals, function(goal) {
            return goal.id === id;
        });
    }
    
    alert(getGoal(2).name);
    

    您可以在jsFiddle 中看到这一点。

    【讨论】:

    • 我喜欢这个答案,因为问题是要求返回单个项目,所以 _.find() 似乎比 _.where() 更合适。通常,当我传入一个 ID 时,我期望一个结果或零而不是可能的项目数组。
    • 嘿 Gwyn,jsfiddle 链接很棒,但在帖子正文中也包含代码通常是个好主意。如果 jsfiddle 链接断开,您的回答对未来的访问者将毫无用处。请考虑使用edit 将代码包含在正文中,以帮助确保这在未来几年对其他人有所帮助。希望这会有所帮助!
    • 感谢编辑!我为您添加了 jsFiddle 链接。这仍然很有帮助,但现在人们可以决定是否需要更多信息,如果需要,请单击链接,或者直接使用页面上的内容。简而言之,链接仍然很酷,只是不是自己。 :)
    猜你喜欢
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2018-03-29
    • 1970-01-01
    相关资源
    最近更新 更多