Remove object from array of objects

前端 未结 9 1484
滥情空心
滥情空心 2021-01-31 15:28

I have an array of objects:

[{\"value\":\"14\",\"label\":\"7\"},{\"value\":\"14\",\"label\":\"7\"},{\"value\":\"18\",\"label\":\"7\"}]

How I ca

9条回答
  •  臣服心动
    2021-01-31 15:55

    Here is a way to do it without 'creating a new array' or using external libraries. Note that this will only remove the first instance found, not duplicates, as stated in your question's example.

    // Array to search
    var arr = [{"value":"14","label":"7"},{"value":"14","label":"7"},{"value":"18","label":"7"}];
    
    // Object to remove from arr
    var remove = {"value":"14","label":"7"};
    
    // Function to determine if two objects are equal by comparing
    // their value and label properties
    var isEqual = function(o1, o2) {
        return o1 === o2 || 
            (o1 != null && o2 != null && 
             o1.value === o2.value &&
             o1.label === o2.label);
    };
    
    // Iterate through array and determine if remove is in arr
    var found = false;
    var i;
    for(i = 0; i < arr.length; ++i) {
        if(isEqual(arr[i], remove)) {
            found = true;
            break;
        }
    }
    
    if(found) {
        // Found remove in arr, remove it
        arr.splice(i, 1);
    }
    

    Demo

提交回复
热议问题