[英]Deleting a row from javascript object
I have a javascript object which looks like this :- 我有一个JavaScript对象,看起来像这样:-
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
. 现在,我必须删除ID值为
2
的对象中的所有行。 How can this be done ? 如何才能做到这一点 ?
Note that what you call myObject
is actually an array therefore you can use array methods on it: 请注意,所谓的
myObject
实际上是一个数组,因此可以在其上使用数组方法:
myObject = myObject.filter(function( obj ) {
return obj.id != 2;
});
Demo: http://jsfiddle.net/elclanrs/LXpYj/ 演示: http : //jsfiddle.net/elclanrs/LXpYj/
If you don't need the original array after "deleting" rows, you can use splice
like this: 如果在“删除”行后不需要原始数组,则可以使用如下
splice
:
http://jsfiddle.net/rmcu5/1/ 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.
如果需要原始数组及其所有项目,请使用其他解决方案之一,该解决方案将为您返回原始数组的修改后的副本。
try this: 尝试这个:
function deleteObject(array,id)
{
var newObject=[];
for (var o in array) {
if(array[o].id!=id)
newObject.push(array[o]);
}
return newObject;
}
You can do without creating new array, you need to write remove function: 您可以在不创建新数组的情况下执行操作,您需要编写remove函数:
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;
};
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;
});
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 jsFiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.