使用简单的map和filter es6过滤现有的对象数组

时间:2018-03-25 10:00:53

标签: javascript ecmascript-6

尽量避免使用任何库,因为我只需要一个简单的脚本。我想从现有数组中获取非现有记录。

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'}],缺少什么?我无法发现它。

5 个答案:

答案 0 :(得分:1)

您可以使用find进行过滤。



var input = [{ name: 'james' }, { name: 'jane' }],
    existing = [{ name: 'james' }],
    result = input.filter(({ name }) => !existing.find(o => o.name === name));
    
console.log(result);




答案 1 :(得分:1)

Array.prototype.filterArray.prototype.mapSet可以使用closure进行组合,以使用{{arrays objects来检测keys之间缺少的元素1}}。

请参阅下面的实例。

// 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)

答案 2 :(得分:0)

您可以使用两个Array#filter的组合。

第一个循环遍历input数组,而第二个循环遍历existing数组,以检查input内是否包含每个existing值。< / p>

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以使用filterfind

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 4 :(得分:-1)

首先,不要重复使用变量名称,这会令人困惑(你有两个单独的东西叫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);

MDN Array.prototype.some