1

I have an array that is stored in a key, see values format:

{id: 0, data: mydata}

I also have a list that corresponds to that ID for deletion of a file and removal of an element.
The problem I am having is when using a Javascript splice function (to delete an object from the array) it changes the index values.

See javascript below:

function setupFileList(file, id){
    var list_of_file = document.getElementById("list_of_file");
    var name_of_file = file.name;
    var size_of_file = 0;
    var file_reader = new FileReader();
    file_reader.onload = function(e){
        var imgsrc = e.target.result;
        if(file){
            if(file.size > 1024 * 1024)
                size_of_file = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + "MB";
            else
                size_of_file = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
        }

        list_of_file.innerHTML += '<div id="file-'+id+'" class="filesUp"><img class="imgUp" src="' + imgsrc +'" width="100px" height="100px"><div class="progressUp"><span>' + name_of_file + ' / ' + size_of_file +'</span></div><a href="#" onclick="deleteUp(\''+id+'\')">Delete</a></div>';
    };
    file_reader.readAsDataURL(file);
};


function deleteUp(fid){
    var file_query = fileQuery.indexOf({id: fid});
    fileQuery.splice(file_query, 1);
    console.log(file_query);
}
1
  • What's wrong with changing the index values? Commented Feb 4, 2013 at 22:41

1 Answer 1

5

How about storing the objects in an object INSTEAD of an array, that way the keys are fixed.

var fileQuery = {
   0: {
      id: 0,
      data: "some data"
   },
   1: {
      id: 1,
      data: "some more data"
   }
};

Use the delete command to remove items from the object.
for example:

delete fileQuery[0];

ALSO indexOf does not compare the properties of objects in an array BUT rather the references of the objects themselves. This means array.indexOf returns the index of the object you give as the arg, so {id: fid} is actually creating a new unique object at that point. Unfortunately indexOf will always return -1 as it will never find the newly created object in the array.

The best way to find the index of the object you are looking for is to manually loop through the array and compare the id property of all elements to fid. I am afraid in this case array.indexOf wont work.

Sign up to request clarification or add additional context in comments.

1 Comment

am going to look at changeing to using an object. i was not aware of that with indexOf so thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.