Skip to content
Advertisement

How to read the current object data when Javascript .some() returns true?

In my project I have an array, holding thousands of objects. I need to search for an explicit object inside the array. When the match is found, I need to be able to access the object properties. Because of performance I want to use Javascript’s .some() function. But with the code I have so far I only get a ‘true’ as return. How can I access the properties inside when the if-statement is a hit?

My code:

let array = [
            {object.uid: 'one',
             object.value: 'Hello one'},
            {object.uid: 'two',
             object.value: 'Hello two'},
            {object.uid: 'three',
             object.value: 'Hello three'}]

if (array.some(e => e.uid == "two")){
   //how do I get object.value here?
};

Advertisement

Answer

You need to use find() method instead of some()

let array = [
            {uid: 'one',
             value: 'Hello one'},
            {uid: 'two',
             value: 'Hello two'},
            {uid: 'three',
             value: 'Hello three'}]
const obj = array.find(e => e.uid == "two");
if (obj){
   console.log(obj)
};
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement