簡體   English   中英

從對象數組中刪除對象

[英]remove object from object array

您好,我試圖從擁有的對象數組中刪除對象,然后創建另一個新對象(我正在使用$ .map()創建新對象)

要從object(x)中刪除此對象,它是object.number必須與array(y)中數字之一匹配

以下代碼有效,但我只刪除了具有object.number = 40 DEMO的對象

代碼:

   var x =[ //this is the object 
  {name : 'mark' , number : '10' , color:'green'},
  {name : 'jeff' , number : '15' , color:'blue'} ,
  {name : 'joy' , number : '30' , color:'yellow'},
  {name : 'mick' , number : '15' , color:'red'},
  {name : 'mick' , number : '40' , color:'black'}] ; 

      var y =['40','15']; // i need to remove all object.number that match the 
        // number in this array

     var newObject = $.map(x  ,function(index, value){
        for(i in y){
         if(index.number == y[i])
        {return null ; }
       else{
        return index;
            }      
      }

    });
 console.log(newObject);​

上面的代碼僅刪除了object.number中包含40的對象,我該如何進行這項工作?

這就是你想要的:

var newObject = $.map(x  ,function(index, value){
    for(i in y){
        if(index.number == y[i])
            return null;
    }
    return index;
});
console.log(newObject);​

jsFiddle 順便說一句:我認為對數組使用for(i in y)不是一個好習慣(數組可能具有其他屬性)。 您應該使用標准:

var l = y.length;
for(var i = 0; i < l; i++){
    /* the other code */
}

注意長度緩存。

試試這個代碼:

var newObject = $.map(x, function(index, value){  
    return (y.indexOf(index.number) != -1) ? null : index;
});

http://jsfiddle.net/Dc68W/

嘗試如下更改功能,

var newObject = $.map(x, function(value, index) {   
   if ($.inArray(value.number, y) == -1) {
       return value;
   } else {
       return null;
   }
});

演示: http : //jsfiddle.net/skram/C3d9T/7/

使用以下內容:

var newObject = $.map($.makeArray(x), function(index, value){  
    return y.indexOf(index.number) != -1 ? null : index;
});

$.makeArray()不是必需的,但如果陣列中可以包含無序數據,則建議使用。

我在這里更新了你的小提琴。 基本上,您並沒有檢查delete數組中的每個值。

var x =[
{name : 'mark' , number : '10' , color:'green'},
{name : 'jeff' , number : '15' , color:'blue'} ,
{name : 'joy' , number : '30' , color:'yellow'},
{name : 'mick' , number : '15' , color:'red'},
{name : 'mick' , number : '40' , color:'black'}] ; 

var y =['40','15'];

var newObject = $.map(x  ,function(index, value){

    var valid = true;
    for(var i = 0; i < y.length; i++){

        if(index.number == y[i])
           valid = false;             
    }
    if(valid)return index;
    else return null;
    });
console.log(newObject);​

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM