Reputation: 73
I have this array:
{"actividades":[
{"id_miembro":"V-005","id_dpto":"D-01","id_actividad":"AC-04","id_seccion":"S-03"},
{"id_miembro":"V-006","id_dpto":"D-01","id_actividad":"AC-01","id_seccion":"S-02"},
{"id_miembro":"V-007","id_dpto":"D-01","id_actividad":"AC-02","id_seccion":"S-01"},
{"id_miembro":"V-008","id_dpto":"D-01","id_actividad":"AC-03","id_seccion":"S-01"}
]}
How can i get the index of the array when "id_miembro" = "V-007"
to delete this data from array?
Upvotes: 0
Views: 70
Reputation: 33870
Other answer are great for removing an element by in an array, but in case you want the index, here a little function for you :
function getIndex(arr, key, val, single){
var rArr = $.map(arr, function(obj, i){
if(obj[key] === val) return i;
});
return single ?
(rArr.length ? rArr[0] : -1):
rArr;
}
You can the call it like that :
var myIndex = getIndex(obj.actividades, 'id_miembro', 'V-007', true);
Where parameters goes like this :
Here's a live example : http://jsfiddle.net/wLDR2/
Upvotes: 0
Reputation: 72857
Simply using JavaScript's Array.prototype.filter()
:
Assuming:
myObj = {"actividades":[
{"id_miembro":"V-005","id_dpto":"D-01","id_actividad":"AC-04","id_seccion":"S-03"},
{"id_miembro":"V-006","id_dpto":"D-01","id_actividad":"AC-01","id_seccion":"S-02"},
{"id_miembro":"V-007","id_dpto":"D-01","id_actividad":"AC-02","id_seccion":"S-01"},
{"id_miembro":"V-008","id_dpto":"D-01","id_actividad":"AC-03","id_seccion":"S-01"}
]}
Then:
myObj.actividades = myObj.actividades.filter(function(e){
return e.id_miembro !== "V-007";
});
(.filter
returns the filtered array. I'm assigning it to the old object, as a replacement, but you can use it in any variable you want, of course)
However, .filter()
's IE support is IE 9+. You might want to use the plyfill provided in the MDN link if you want to support older browsers.
Upvotes: 0
Reputation: 42048
It's easy with a library like Lo-Dash:
var index = _.findIndex(array.actividades, { 'id_miembro': 'V-007' });
See it on JSFiddle.
Upvotes: -1
Reputation: 67207
You can do that with $.grep()
,
var newArray = $.grep(xObj.actividades,function(val,i){
return val.id_miembro !== "V-007";
});
Note: i just assume that you are having that JSON in a variable called xObj
API: http://api.jquery.com/jquery.grep/
Upvotes: 3