Remove object from a JavaScript Array?

Possible Duplicate:
Remove specific element from a javascript array?

Specifically I have an array as follows:

var arr = [
    {url: 'link 1'},
    {url: 'link 2'},
    {url: 'link 3'}
];

Now you want to remove valuable element url "link 2" and after removing the only arrays as follows:

arr = [
    {url: 'link 1'},
    {url: 'link 3'}
];

So who can help me this problem? Thanks a lot


You could do a filter.

var arr = [
  {url: "link 1"},
  {url: "link 2"},
  {url: "link 3"}
];

arr = arr.filter(function(el){
  return el.url !== "link 2";
});

PS: Array.filter method is mplemented in JavaScript 1.6, supported by most modern browsers, If for supporting the old browser, you could write your own one.


Use the splice function to remove an element in an array:

arr.splice(1, 1);

If you would like to remove an element of the array without knowing the index based on an elements property, you will have to iterate over the array and each property of each element:

for(var a = 0; a < arr.length; a++) {
    for(var b in arr[a]) {
        if(arr[a][b] === 'link 2') {
            arr.splice(a, 1);
            a--;
            break;
        }
    }
}
链接地址: http://www.djcxy.com/p/3204.html

上一篇: 如何在javascript中删除数组中的特定元素

下一篇: 从JavaScript数组中删除对象?