0

say I have an array

var test = [{a: 26, b:14, c:null},{d:67, e: 8}];

say I want the value of c, I don't know what value c will have or which array will have c;

I was thinking of using $.grep but it does seem like I could use it in that way

So how do I go about getting the value of c?

EDIT

Just test as per my comment you can do

$.grep(test,function(e){return e.hasOwnProperty('c')})

This will return the array that has the object/objects of the property you want

1
  • 1
    Try test.filter(function(x){return "c" in x}).map(function(x){return x.c}).forEach(alert) - or, with jQuery, $.each($.map($.grep(test, function(x){return "c" in x}), function(x){return x.c}), alert) Commented Oct 2, 2014 at 15:24

1 Answer 1

2

You'll want to make use of hasOwnProperty here:

for (var i = 0; i < test.length; i++) {
    if (test[i].hasOwnProperty('c')) {
        alert(test[i].c); // do something with test[i].c
        break; // assuming there is only ever 1 item called c, once we find it we can break out of the whole loop.
    }
}

As you suggested, $.grep would work too:

var objectsThatHaveC = $.grep(test, function(obj) {
    return obj.hasOwnProperty('c');
});

if (objectsThatHaveC.length) {
    alert(objectsThatHaveC[0].c); // assuming there's only 1 object with a 'c', otherwise you'd still have to loop here
}
Sign up to request clarification or add additional context in comments.

4 Comments

You missed the closing ) for if. Other than that, this works good.
out of curiosity how would you go about using grep for this, I was thinking of something like 'var hope = $.grep(test,function(e){return e.c == something})' but can't figure out what that some would be unless you could do 'var hope = $.grep(test,function(e){return e.hasOwnProperty('c')})'
@SamStephenson Yep, that would do it. You just need it to return true/false for whether to keep that obj or not, so your prediction is spot on. var objThatHasC = $.grep(test, function(obj) { return obj.hasOwnProperty('c') }); alert(objThatHasC.c);. Your right, maybe that would be easier than the loop ;-) adding it to my answer.
Correction – the $.grep would return an array, so you'd then need to do objectsThatHaveC[0].c. See updated answer.

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.