如何通过对象属性在对象数组中查找对象?

编程入门 行业动态 更新时间:2024-10-18 05:56:13
本文介绍了如何通过对象属性在对象数组中查找对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有对象数组.在每个对象中,我都有属性ID.

I have array of objects. In each object i have property id.

for(var i=0;i<listItems.length;i++){ if(listItems[i].id==5){ var selectedDataEdit=JSON.stringify(listItems[i]); } }

我想找到id = 5的对象.现在我用循环来做.但这是一个漫长的过程.有没有办法做到无循环?

I want to find object where id=5. Now i do it using loop. But it is a long process. Is there a way to do it without loop?

推荐答案

这确实取决于您的特定需求,因此我们需要更多信息(为什么要花很长时间?这个过程的目标是什么?) ,但是一种非常简单的方法是在索引为id的情况下创建另一个数组(假设id是唯一的).

It really depends on your specific needs so we need more information (why is it a long process? what is the goal of this process?) for a good answer, but one very simple approach would be to create another array that where the index is id (assuming the id is unique).

var listItemsById = []; for(var i=0;i<listItems.length;i++){ listItemsById[listItems[i].id] = listItems[i]; }

此后,您可以使用listItemsById通过id快速访问任何项目,同时仍保留原始listItems(因为listItemsById中的项目仅是对原始项目的引用).

After this, you can quickly access any item by id using listItemsById while still preserving the original listItems (because the items in listItemsById are only references to the originals).

更新:由于我看到有人建议使用.filter(或等效版本),因此我认为需要明确的一件事是, 安迪指出,有(至少)两种方法可以将原始代码视为漫长的过程":

UPDATE: Since I see several people have suggested using .filter (or an equivalent), I think that one of the things that needs to be made clear, as Andy pointed out, is that there are (at least) two ways you can consider the original code a "long process":

1.花费(相对)较长的时间(或者看时不太清楚)

如果这是您的关注点,那么.filter是一个干净的解决方案,但请记住,它的执行速度不是 (实际上,它可能是比使用循环要慢,但这取决于实现方式).它仍然会在内部使用某种循环,并且如果您编写自己的函数,您将得到相同的结果,例如:

If this is your concern, then .filter is a clean solution, but keep in mind that it is not faster to execute (it may, in fact, be slower than using a loop, but this is implementation-dependent). It will still internally use a loop of some sort and you would get the same result if you wrote your own function, for example:

function findById(items, id) { for(var i=0; i<items.length; i++){ if (items[i].id==id){ return items[i]; } } } // example call var selectedDataEdit=JSON.stringify(findById(listItems, 5));

2.执行时间很长

如果是这种情况,那么您需要提供有关使用的更多信息.虽然我最初提供的解决方案会更快,但它非常笼统,在您的特定情况下可能不是一个好主意(甚至可能不适用).

If this is the case, then you need to provide more information on the use. While the solution I initially provided would be faster, it's very general and may not be a good idea (or may not even be applicable) in your particular case.

更多推荐

如何通过对象属性在对象数组中查找对象?

本文发布于:2023-11-07 06:00:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565723.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   组中   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!