0

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

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?

5 Answers 5

1

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

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

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. It takes you a (relatively) long time to write (or not very clear when looking)

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. It takes a long time to execute

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for "It will still internally use a loop of some sort and you would get the same result if you wrote your own function". My thoughts exactly.
0

You can use jquery .filter() function:

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

3 Comments

Is this code really using a "jQuery" filter function?
@R3tep. Which means it should not be referred to as jquery .filter() function. A thin line to watch: A jQuery .filter() function indeed exists and works like this: jQuery('#selector').filter() on DOM collection objects.
i am actually referring to jquery filter. for javascript filter you need to pass current obj as argument for using inside the filter function.
0

I usually use lo-dash for these type of operations. You might find usefull this library. In your case i would use _.findWhere.

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

Comments

0

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.

On filter: as the others have mentioned filter is a reasonable alternative. 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.

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

Comments

-1

This may do the trick

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

Hope it Works

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.