比较两个对象数组,并将匹配值的元素排除在JS中的新数组中 [英] Comparing two arrays of objects, and exclude the elements who match values into new array in JS

查看:248
本文介绍了比较两个对象数组,并将匹配值的元素排除在JS中的新数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在JavaScript中的用例:

here is my use case in JavaScript:

我有两个对象数组,它们具有匹配的属性(id& name)。

I have two arrays of objects which have properties that match (id & name).

var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}
];

var result2 = [
    {id:2, name:'John', email:'johnny@example.com'},
    {id:4, name:'Bobby', email:'bobby@example.com'}
];

var props = ['id', 'name'];

我的目标是让另一个对象数组只包含不匹配的元素。像这样:

My goal is to have another array of objects containing only the elements which did not match. Like this:

var result = [
    {id:1, name:'Sandra'},
    {id:3, name:'Peter'}
];

我知道有一种方法可以通过从result1比较每个对象与对象result2,然后比较他们的键,如果没有匹配,将值放在另一个对象然后将其推入新数组,但我想知道是否有更优雅的方式,如使用lo-dash或下划线或类似的东西。

I know that there is a way of doing this by going from result1 compare each object with the objects of result2, then compare their keys, and if did'n match, put the values in another object then push it in new array, but I wonder is there any more elegant way, like using lo-dash or underscore or something similar.

谢谢!

推荐答案

只需使用数组迭代方法适用于此:

var result1 = [
    {id:1, name:'Sandra', type:'user', username:'sandra'},
    {id:2, name:'John', type:'admin', username:'johnny2'},
    {id:3, name:'Peter', type:'user', username:'pete'},
    {id:4, name:'Bobby', type:'user', username:'be_bob'}
];

var result2 = [
    {id:2, name:'John', email:'johnny@example.com'},
    {id:4, name:'Bobby', email:'bobby@example.com'}
];

var props = ['id', 'name'];

var result = result1.filter(function(o1){
    // filter out (!) items in result2
    return !result2.some(function(o2){
        return o1.id === o2.id;          // assumes unique id
    });
}).map(function(o){
    // use reduce to make objects with only the required properties
    // and map to apply this to the filtered array as a whole
    return props.reduce(function(newo, name){
        newo[name] = o[name];
        return newo;
    }, {});
});

document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) +
        '</pre>';

如果你是做了很多,然后一定要看外部图书馆来帮助你,但是首先要学习基础知识,并且基础知识将在这里很好地为你服务。

If you are doing this a lot, then by all means look at external libraries to help you out, but it's worth learning the basics first, and the basics will serve you well here.

这篇关于比较两个对象数组,并将匹配值的元素排除在JS中的新数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆