本文介绍了从javascript对象删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的javascript对象:-
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"}];
现在,我必须删除ID值为的对象中的所有行2
。
Now , I have to delete all the rows in the object with id value 2
. How can this be done ?
推荐答案
如果删除行后不需要原始数组,则可以使用 splice
像这样:
If you don't need the original array after "deleting" rows, you can use splice
like this:
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.
这篇关于从javascript对象删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!