简体   繁体   English

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

[英]How to find object in array of object by object property?

I have array of objects. 我有对象的数组。 In each object i have property id. 在每个对象中,我都有属性ID。

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

I want to find object where id=5. 我想找到id = 5的对象。 Now i do it using loop. 现在我使用循环来做。 But it is a long process. 但这是一个漫长的过程。 Is there a way to do it without loop? 有没有办法做到没有循环?

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

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

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

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": 更新:由于我看到有几个人建议使用.filter (或等效方法),因此我认为,正如Andy指出的,需要弄清楚的一件事是,至少有两种方法可以考虑原始代码是一个“漫长的过程”:

1. It takes you a (relatively) long time to write (or not very clear when looking) 1.花费(相对)较长的时间来书写(或看时不太清楚)

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). 如果这是你的关心,那么.filter是一个干净的解决方案,但请记住,这不是更快的执行(它可能,事实上,是比使用一个循环较慢 ,但这是依赖于实现)。 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. It takes a long time to execute 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. 虽然我最初提供的解决方案会更快,但是它非常笼统,在您的特定情况下可能不是一个好主意(甚至可能不适用)。

You can use jquery .filter() function: 您可以使用jquery .filter()函数:

JSON.stringify(listItems.filter(function(){
   return this.id==5;
}))

I usually use lo-dash for these type of operations. 我通常将lo-dash用于此类操作。 You might find usefull this library. 您可能会发现此库有用。 In your case i would use _.findWhere . 在您的情况下,我将使用_.findWhere

https://jsfiddle.net/cfcef9nu/2/ https://jsfiddle.net/cfcef9nu/2/

What's the long process involved with the loop? 循环涉及什么漫长的过程? Writing it? 写吗 That it's taking too long to process the elements? 处理这些元素需要太长时间吗? Perhaps you can reorganise your data structure to help with this by, as fstanis suggests, using the id as the key in an object, but if you want to use an array a loop will always be necessary. 正如fstanis所建议的那样,也许您可​​以重组数据结构以帮助实现此目的,方法是使用id作为对象中的键,但是如果要使用数组,则总是需要循环。

On filter : as the others have mentioned filter is a reasonable alternative. 关于filter :正如其他人提到的, filter是一个合理的选择。 However, if you decide to use this method, you need to understand that filter returns an array , so you want a function that returns the first element of that array, and in your case, the stringified version of that element. 但是,如果决定使用此方法,则需要了解filter返回一个array ,因此您需要一个函数来返回该数组的第一个元素,以及返回该元素的字符串化版本的函数。

function findById(arr, id) {
  var result = arr.filter(function (el) { return el.id === id; });
  return JSON.stringify(result[0]);
}

findById(arr, 5); // "{"id":3,"no":32}"

DEMO 演示

This may do the trick 这可能会解决问题

var item = listItems.filter(function (e) {if (e.id == 5) return JSON.stringify(e);});

Hope it Works 希望它能工作

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

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