filter array of objects by another array of objects

后端 未结 4 1954
日久生厌
日久生厌 2020-12-08 23:22

I want to filter array of objects by another array of objects.

I have 2 array of objects like this:

const array = [
    { id: 1, name: \'a1\', sub: {         


        
4条回答
  •  温柔的废话
    2020-12-09 00:02

    You could use JSON.stringify to compare the two objects. It would be better to write a function that compares all properties on the objects recursively.

    const array = [
        { id: 1, name: 'a1', sub: { id: 6, name: 'a1 sub' } },
        { id: 2, name: 'a2', sub: null },
        { id: 3, name: 'a3', sub: { id: 8, name: 'a3 sub' } },
        { id: 4, name: 'a4', sub: null },
        { id: 5, name: 'a5', sub: { id: 10, name: 'a5 sub' } },
    ];
    const anotherArray = [
        { id: 1, name: 'a1', sub: { id: 6, name: 'a1 sub' } },
        { id: 2, name: 'a2', sub: null },
        { id: 5, name: 'a5', sub: { id: 10, name: 'a5 sub' } },
    ];
    
    const notIn = (array1, array2) => array1.filter(item1 => {
        const item1Str = JSON.stringify(item1);
        return !array2.find(item2 => item1Str === JSON.stringify(item2))
      }
    );
    
    console.log(notIn(array, anotherArray));

提交回复
热议问题