2016-06-09 13 views
1

我有2個對象/數組:最有效的方式,通過一個對象和陣列定位匹配來搜索

var objA = { 
    Red Chair : "DC10291", 
    USBDongle : "USKI82322", 
} 

var arrayB = [ 
    { 
     field: "Yellow Banana", 
     id: "Yellow Banana" 
    }, 
    { 
     field: "Red Chair", 
     id: "Red Chair" 
    }, 
    { 
     field: "Garden", 
     id: "Garden" 
    } 
] 

我所要做的是,如果一個KEYobjA,例如Red Chair,存在於arrayB中,然後將其從arrayB中刪除。

我已經這樣做了:

var arrayClone = _.cloneDeep(arrayB); 
var removeThese = []; 

Object.keys(arrayClone).forEach(function(p) { 
    removeThese.push(p) 
}); 


removeThese.forEach(function(remove) { 
    arrayB.forEach(function(item) { 
     if(item.id === remove) { 
      delete objA[remove]; 
     } 
    }); 
}); 

上述作品如預期,但是這是最effieicnt?我問的Reasone是因爲循環throuhg和數組在循環內不感覺最佳做法?也就有了性能的影響

+0

做你想做的'arrayB'陣列將保持不變,並移除'objA'匹配的屬性? – RomanPerekhrest

回答

2

你可以簡單地將其過濾,這樣

_.filter(arrayB, obj => !objA.hasOwnProperty(obj.field)) 
// [ { field: 'Yellow Banana', id: 'Yellow Banana' }, 
// { field: 'Garden', id: 'Garden' } ] 

這將使用ES2015的箭函數的語法。你可以寫一個正常的功能相同這樣

arrayB.filter(function(obj) { 
    return !objA.hasOwnProperty(obj.field); 
}); 
// [ { field: 'Yellow Banana', id: 'Yellow Banana' }, 
// { field: 'Garden', id: 'Garden' } ] 

我們基本上是過濾掉,其field值是objA關鍵中的所有對象。

+0

謝謝,對不起,這是新的...過濾器後如何刪除? –

+0

@OamPsy你的意思是,你想從'arrayB'中移除值嗎? – thefourtheye

+0

不好意思,我的意思是我該如何刪除objA –

1

如果你想保留原來的arrayB,並根據你的條件得到它的縮小版本,然後Array.prototype.reduce()這樣做與O(n)的時間複雜性。但是,如果您想要執行此操作,那麼Array.prototype.reduceRight()會以O(n)時間複雜度來執行此操作。

var objA = { 
 
    "Red Chair" : "DC10291", 
 
    "USBDongle" : "USKI82322", 
 
}, 
 

 
arrayB = [ 
 
    { 
 
     field: "Yellow Banana", 
 
     id: "Yellow Banana" 
 
    }, 
 
    { 
 
     field: "Red Chair", 
 
     id: "Red Chair" 
 
    }, 
 
    { 
 
     field: "Garden", 
 
     id: "Garden" 
 
    } 
 
], 
 

 
arrayC = arrayB.reduce((p,c) => !objA[c.field] ? p.concat(c) : p, []); 
 
console.log(arrayC); 
 
arrayB.reduceRight((p,c,i,a) => (p[c.field] && a.splice(i,1),p),objA); 
 
console.log(arrayB);

相關問題