[英]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.