简体   繁体   中英

JavaScript get value or property of an Array of objects if object has that property

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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