简体   繁体   中英

Finding element in Javascript object array

I have a javascript object array like

var objArr = [Object{key="1", value="a"}, Object{key="2", value="b"}, ...]

Do we have any Jquery method find the object and delete it. I know using $.each

$.each(objArr, function(index, obj) {

})

But do we have any easy and efficient solution for this?

Without jQuery, by simply using the filter function of javascript :

var filtered = objArr.filter(function(o){return o.key!='badkey';});

(note that the MDN page offers tips for the compatibility with very old browsers)

To find the element you could use the .grep() function Example:Filter an array of numbers to include numbers that are not bigger than zero.

$.grep( [0,1,2], function(n,i){
return n > 0; 
},true);

Result: [0]

Or if you only need to find the position of that element, you could use the .inArray() function Example: Find the position of the element that matches with: "1"

var arr = [ 4, 2, 3, 1, "hello" ];
var exist = $.inArray(1, arr);

Result:

exist = 3

And for delete, theres a post that maybe can resolve your problem How to remove specifc value from array using jQuery

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