如何通过对象属性在对象数组中查找对象? [英] How to find object in array of object by object property?

查看:612
本文介绍了如何通过对象属性在对象数组中查找对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象数组.在每个对象中,我都有属性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.

这篇关于如何通过对象属性在对象数组中查找对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆