0

I have a number of objects passed to a function as an argument such as:

$( document ).on( "custom.event", function( evt, obj ) {
    console.log( obj );
});

The objects look like this (in console):

Object {name: "obj1", property: "", somethingElse: "some value"}
Object {name: "obj2", property: "1", somethingElse: "some value"} //I want this one!
Object {name: "obj3", property: "", somethingElse: "some value"}
Object {name: "obj4", property: "1", somethingElse: "some value"}

I would like to make use of the FIRST object where property is equal to "1" and have at my disposal the rest of the properties and their values (from said obj). How might I do this? I've tried $.each but couldn't work out how to only return the first object where property == "1".

Thanks

3 Answers 3

2

You could use $.each to loop through the elements and use return false to break the loop when you find the first object:

var searchedObject = null;
$.each(obj, function(index, el) {
    if (el.property == "1") {
        searchedObject = el;
        return false;
    }
});

If you aren't worried about IE8 or below, you could also use Array.prototype.filter()

var searchedObject = obj.filter(function(el) {
    return el.property == "1"
})[0]; // [0] to get the 1st element.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, great answer.
@Myles It's also worth noting that @Curt's answer is the fastest since it's plain javascript. The .filter method will check every element and $.each has overhead.
1

Iterate through the array and store a reference when an item matches the property value required.

var first1Obj;

for(i=0; i<=obj.length; i++){
   if (obj[i].property == "1"){
       first1Obj = obj[i];
       break;
    }
}

See Demo: http://jsfiddle.net/7vmbs95t/

1 Comment

Thanks! Perfect solution.
1

check if this works for you: https://jsfiddle.net/leojavier/83wt0vvg/

var obj = [
 {name: "obj1", property: "", somethingElse: "some value"},
 {name: "obj2", property: "1", somethingElse: "some value"},
 {name: "obj3", property: "", somethingElse: "some value"},
 {name: "obj4", property: "1", somethingElse: "some value"}]

 for(item in obj) {
  if(obj[item].property == 1) {
    console.log(obj[item].name)
    break;
  }

 }

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.