remove objects from array by object property

前端 未结 13 2798
抹茶落季
抹茶落季 2020-11-22 17:40
var listToDelete = [\'abc\', \'efg\'];

var arrayOfObjects = [{id:\'abc\',name:\'oh\'}, // delete me
                      {id:\'efg\',name:\'em\'}, // delete me
            


        
相关标签:
13条回答
  • 2020-11-22 18:08

    If you like short and self descriptive parameters or if you don't want to use splice and go with a straight forward filter or if you are simply a SQL person like me:

    function removeFromArrayOfHash(p_array_of_hash, p_key, p_value_to_remove){
        return p_array_of_hash.filter((l_cur_row) => {return l_cur_row[p_key] != p_value_to_remove});
    }
    

    And a sample usage:

    l_test_arr = 
    [
        {
             post_id: 1,
            post_content: "Hey I am the first hash with id 1"
        },
        {
            post_id: 2,
            post_content: "This is item 2"
        },
        {
            post_id: 1,
            post_content: "And I am the second hash with id 1"
        },
        {
            post_id: 3,
            post_content: "This is item 3"
        },
     ];
    
    
    
     l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 2); // gives both of the post_id 1 hashes and the post_id 3
     l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 1); // gives only post_id 3 (since 1 was removed in previous line)
    
    0 讨论(0)
提交回复
热议问题