简体   繁体   English

Lodash比较不同长度的对象数组

[英]Lodash compare array of objets different length

I'm using lodash to compare two arrays of objets with differentWith (isEqual) function.我正在使用 lodash 比较两个 arrays 对象与 differentWith (isEqual) function。

Here my two arrays:这是我的两个 arrays:

array1数组1

[
    {
        "id":"28884",
        "designation":"French fries",
        "description":"French fries",
        "prices":[ 
            { 
            "price":0,
            "vat":2821
            }
        ]
    },
    {
        "id":"28885",
        "designation":"Potatoes",
        "description":"Potatoes",
        "prices":[ 
            { 
            "price":0,
            "vat":2821
            }
        ]
    }
]

array2数组2

[
    {
        "id":"28884",
        "designation":"French fries",
        "description":"French fries",
        "prices":[ 
            { 
            "price":0,
            "vat":2821
            }
        ]
    },
    {
        "id":"28885",
        "designation":"Potatoes",
        "description":"Potatoes",
        "prices":[ 
            { 
            "price":0,
            "vat":2821
            }
        ]
    },
    {
        "id":"30157",
        "designation":"new item",
        "description":null,
        "prices":[ 
            { 
                "price":500,
                "vat":2821
            }
        ]
    }
]

Here what I did but it doesn't work:这是我所做的,但它不起作用:

const toAdd = _.differenceWith(array1, array2, _.isEqual);
const toRemove = _.differenceWith(array2, array1, _.isEqual);

How can I get removed element(s)?我怎样才能删除元素? Moreover, How can I get the new elements, removed elements using lodash?此外,如何使用 lodash 获取新元素、删除元素? Thank you !谢谢 !

The problem is the comparator in the code _.isEqual cannot compare two objects in the array.问题是代码_.isEqual中的比较器无法比较数组中的两个objects You could write a custom comparator.您可以编写一个自定义比较器。

A simpler vanilla js option may be一个更简单的 vanilla js 选项可能是

removedObjectsArray = array2.filter(item => !array1.map(obj => obj.id).includes(item.id));

Here the larger array is filtered to find items which have an id that is not in the smaller array.这里过滤较大的数组以查找具有不在较小数组中的 id 的项目。

You can use _.differenceBy.您可以使用 _.differenceBy。 _.intersectionBy for comparision with key in case of array of objects. _.intersectionBy 用于在对象数组的情况下与键进行比较。

.differenceBy .differenceBy .intersectionBy .intersectionBy

 let toRemove = _.differenceBy(array2, array1, 'id');
 let toAdd = _.intersectionBy(array1, array2, 'id');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM