Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from Javascript associative array using array value

I am trying to remove an element from a Javascript associtive array using the value to find it, but I am having trouble. I have tried splice and JQuery's grep method and neither have worked for me. This is what I currently have.

var array_path = new Array();

function bulk_upload(){

var temp_array = new Object();

for (var i = 1; i<8; i++){

        temp_array[i] = $('#path' + i).val();

        if(temp_array[i]!='' && temp_array[i]!=null){

            array_path['path' + i] = $('#path' + i).val();

        }

}
process_txt();
}

function process_txt(){

//alert(array_path.indexOf(full_path)); //returns nothing

var removed_element = array_path.splice(getKey(array_path), 1);

//array_path = $.grep(array_path, function(val) { return val != full_path; });

alert(removed_element);//return nothing, just blank alert box

}

function getKey(data) {
  for (var prop in data)
    return prop;
}
like image 343
Abs Avatar asked Nov 23 '09 16:11

Abs


1 Answers

The way to do this is to use the delete operator.

delete array_path[getKey(array_path)]

Some Background Information

In JavaScript, almost everything descends from Object.prototype. JavaScript, being an open and dynamic language allows you to create/modify properties of objects by simple assignment. This is very similar to what an associative array -- a structure that contains keyed values.

Under the hood an array is just an object that descends from Array.prototype with numeric keys and a special property called length. The length property just returns one greater than the highest numeric property. In essence, an Array is an object with different semantics.

If you're wanting an associative array then Array is not the object you want to descend from. You would want to descend directly from Object. There are two ways to do that, you could either use the new operator or an empty object literal. The syntax for both is below:

var o = new Object();
var o = {};

The second is preferred since it's a little bit more concise.

I wrote a blog post about this a while back, have a look if you want a little bit more info.

like image 157
Bryan Kyle Avatar answered Nov 15 '22 06:11

Bryan Kyle