问题
I have a javascript object which looks like this :-
var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
{"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
{"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
Now , I have to delete all the rows in the object with id value 2
. How can this be done ?
回答1:
If you don't need the original array after "deleting" rows, you can use splice
like this:
http://jsfiddle.net/rmcu5/1/
var myArray = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
{"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
{"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
function removeItemsById(arr, id) {
var i = arr.length;
if (i) { // (not 0)
while (--i) {
var cur = arr[i];
if (cur.id == id) {
arr.splice(i, 1);
}
}
}
}
removeItemsById(myArray, "2");
console.log(JSON.stringify(myArray));
It doesn't create a new array, just modifies the original in place. If you need the original array and all of its items, then use one of the other solutions that return you a modified copy of the original.
回答2:
Note that what you call myObject
is actually an array therefore you can use array methods on it:
myObject = myObject.filter(function( obj ) {
return obj.id != 2;
});
Demo: http://jsfiddle.net/elclanrs/LXpYj/
回答3:
try this:
function deleteObject(array,id)
{
var newObject=[];
for (var o in array) {
if(array[o].id!=id)
newObject.push(array[o]);
}
return newObject;
}
working JS fiddle
You can do without creating new array, you need to write remove function:
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
Without New Array Delete Object
回答4:
try it with filter (its an array not a object)
var rr = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"}, {"id": "2", "URL": "http://shsusadhf.com", "value": "2"}, {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
rr = rr.filter(function(e) {
return e.id != 2;
});
回答5:
Here you go, this is without recreating the array or anything.
var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
{"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
{"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
for(i=0,iMax=myObject.length;i<iMax;i++){
(function (a) {
if(this.id=="2"){
delete myObject[a];
}
}).call(myObject[i],i);
}
console.log(myObject);
jsFiddle
http://jsfiddle.net/gG2zz/1/
来源:https://stackoverflow.com/questions/13834338/deleting-a-row-from-javascript-object