[英]filter existing array of object using simple map and filter es6
盡量避免使用任何庫,因為我只需要一個簡單的腳本。 我想從現有數組中獲取不存在的記錄。
input = [{name: 'james'}, {name: 'jane'}]
existing = [{name: 'james'}]
//做一點事
預期的輸入將變為[{name: 'jane'}]
我試過了
let input = [{
name: 'yahoo.com',
},{
name: 'google.my',
}]
existing = (existing || []).map(o => ({name: o.name})) //clean up data from backend [{name:'google.my'}]
input = (input || []).map(o => o.name) //just in case input has more property in the future
input = existing.filter(o => !o.name.includes(input))
console.log(input)
不知何故我仍然沒有得到想要的東西(期望輸入為[{name: 'yahoo.com'}]
,缺少了什么?我找不到它。
您可以使用find
查找過濾。
var input = [{ name: 'james' }, { name: 'jane' }], existing = [{ name: 'james' }], result = input.filter(({ name }) => !existing.find(o => o.name === name)); console.log(result);
可以使用closure
將Array.prototype.filter
, Array.prototype.map
和Set
組合在一起,以使用keys
檢測objects
arrays
之間的缺失元素。
請參見下面的實際示例。
// Input. const input = [{name: 'james'}, {name: 'jane'}] // Existing. const existing = [{name: 'james'}] // Missing (B elements from A). const missing = (A, B) => (s => A.filter(({name}) => !s.has(name)))(new Set(B.map(({name}) => name))) // Output. const output = missing(input, existing) // Proof. console.log(output)
您可以結合使用兩個Array#filter
。
第一個循環遍歷您的input
數組,而第二個循環遍歷您的existing
數組,以檢查每個input
值是否包含在existing
。
let input = [{name: 'james'}, {name: 'jane'}]; let existing = [{name: 'james'}]; let res = input.filter(a => !existing.filter(b => b.name == a.name).length); console.log(res);
您可以使用filter
find
let input = [{name: 'james'}, {name: 'jane'}]; let existing = [{name: 'james'}]; let result = input.filter(v => !existing.find(o => o.name == v.name)); console.log(result);
首先,不要重用變量名,這很容易混淆(您有兩個分開的東西,稱為input
。
第二,不要做不必要的循環。 在大門外做一個過濾器,然后映射以獲取名稱數組(如果您確實不需要,則完全跳過該映射)
let input = [
{
name: 'yahoo.com'
},
{
name: 'google.my'
}
]
//all names in existing that are also in input
(existing || [])
//I used some instead of includes
.filter(o => !(input || []).some(i => i.name == o.name))
.map(o => o.name);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.