简体   繁体   English

Javascript,按ID在对象列表中查找对象

[英]Javascript, find object in list of objects by id

I have a list of objects in where I need to find one specifically by an ID. 我有一个对象列表,需要在其中专门通过ID查找对象。 So very simply like so: 就像这样:

{ 
 {
   "id": "1"
 },{
   "id": "2"
 }
}

I have a function where I want to find the object by it's id, that does not work like so 我有一个函数,我想通过它的id查找对象,它不能像这样工作

 function findOb (id) {

   return _.find(myList, function(obj) { return obj.id === id } );

 }

it is not returning the correct object (this is using lodash) uncertain what I am doing incorrect and could use some help. 它没有返回正确的对象(这是使用lodash),不确定我在做什么错误,可以使用一些帮助。 Thanks! 谢谢!

edit - I don't know if this helps but I am building and trying to search an object in this format - https://github.com/pqx/react-ui-tree/blob/gh-pages/example/tree.js . 编辑 -我不知道这是否有帮助,但是我正在构建并尝试以这种格式搜索对象-https: //github.com/pqx/react-ui-tree/blob/gh-pages/example/tree。 js So there are just objects with module and leaf sometimes, and I want to be able to search and find by the 'module' key. 因此,有时只有带有模块和叶子的对象,我希望能够通过“模块”键进行搜索和查找。 Thanks for the feedback everyone! 感谢大家的反馈!

Your code should have worked, but it can be simplified. 您的代码应该可以使用,但是可以简化。

If you provide a property name for the predicate argument to _.find , it will search that property for the thisArg value. 如果为_.findpredicate参数提供属性名称,它将在该属性中搜索thisArg值。

function findOb(id) {
    return _.find(myList, 'id', id);
}

The only problem I can see with your code is that you use === in your comparisons. 我在您的代码中看到的唯一问题是您在比较中使用=== If you pass 1 as the ID argument instead of "1" , it won't match because === performs strict type checking. 如果将1作为ID参数而不是"1"传递,则它将不匹配,因为===执行严格的类型检查。

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

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