Javascript 下划线js通过ID查找项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12744447/
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-08-23 11:09:48  来源:igfitidea点击:

Underscore js find item by ID

javascriptunderscore.js

提问by Mauro74

I'm new to Underscore js and bit confused on how to use it. I have a collection of 'goals' and I want to find one of it by ID.

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

here's the data:

这是数据:

{"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"
    }
    ...
]}

That's what I'm trying, I want to get the entire array/object so I can get each field of it:

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

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

Any idea how to do it?

知道怎么做吗?

回答by Ahmad Alfy

Update

更新

It's 2016 and we might not acutally need underscore to achieve that. Using Array.prototype.find(). It returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise undefined is returned.

现在是 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'

Browser support

浏览器支持

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

More information an polyfill on MDN

更多关于MDN的 polyfill 信息



Update: I found that _.wherealways returns an array. _.findWherereturns the first object it finds so it will be better to use if you expect a single object in return.

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



You can use _.whereIt's much easier.

你可以使用_.where它更容易。

If it's something like this :

如果是这样的:

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"
    }
]

You can use something like :

你可以使用类似的东西:

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

回答by Ved

You are using Array of objects. So,you can use: _.findWhere(Looks through the list and returns the first value that matches all of the key-value pairs ) to get the all the properties based on id or other key attribute.

您正在使用对象数组。所以,你可以使用:_。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);

To get the index, you can use something like this:

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

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

If you need all list of uses,
TRY: _.where(It looks through each occurrence in the array, returning an array of all the values that contain the key-value pairs listed in properties.)

如果您需要所有使用列表,请
尝试_.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: It is used to check the value only, not Key-value both.

_.find:仅用于检查值,不用于检查Key-value。


Visit Docs:_.find


访问文档:_.find

回答by Gwyn Howell

Have simplified your data model, but something like this?

简化了你的数据模型,但像这样吗?

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);

You can see this in action in this jsFiddle.

你可以在这个jsFiddle 中看到这一点。