How to get the difference between two arrays of objects in JavaScript

前端 未结 18 1071
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 04:45

I have two result sets like this:

// Result 1
[
    { value: \"0\", display: \"Jamsheer\" },
    { value: \"1\", display: \"Muhammed\" },
    { value: \"2\",         


        
18条回答
  •  广开言路
    2020-11-22 05:17

    Most generic and simple way:

    findObject(listOfObjects, objectToSearch) {
        let found = false, matchingKeys = 0;
        for(let object of listOfObjects) {
            found = false;
            matchingKeys = 0;
            for(let key of Object.keys(object)) {
                if(object[key]==objectToSearch[key]) matchingKeys++;
            }
            if(matchingKeys==Object.keys(object).length) {
                found = true;
                break;
            }
        }
        return found;
    }
    
    get_removed_list_of_objects(old_array, new_array) {
        // console.log('old:',old_array);
        // console.log('new:',new_array);
        let foundList = [];
        for(let object of old_array) {
            if(!this.findObject(new_array, object)) foundList.push(object);
        }
        return foundList;
    }
    
    get_added_list_of_objects(old_array, new_array) {
        let foundList = [];
        for(let object of new_array) {
            if(!this.findObject(old_array, object)) foundList.push(object);
        }
        return foundList;
    }
    

提交回复
热议问题