www.webdeveloper.com
Results 1 to 5 of 5

Thread: Array indexOf by Key, Value

  1. #1
    Join Date
    Jan 2013
    Posts
    3

    Exclamation Array indexOf by Key, Value

    I have an array that is stored in a key, value format:
    Code:
    {id: 0, data: some data}
    I have a list that corresponds to that id for deletion of a file and removal of an element. When using javascript splice to delete an object from the array it changes the index values.

    Here is some of the code that I am currently working with to give you an idea of what I am trying to achieve.

    Code:
    function setupFileList(file,id){
    	var filelist = document.getElementById("filelist");
    	var fileName = file.name;
    	var fileSize = 0;
    	var reader = new FileReader();
    	reader.onload = function(e){
    		var imgsrc = e.target.result;
    		if(file){
    			if(file.size > 1024 * 1024)
    				fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + "MB";
    			else
    				fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
    		}
    		
    		filelist.innerHTML += '<div id="file-'+id+'" class="upFiles"><img class="upImg" src="' + imgsrc +'" width="50px" height="50px"><div class="upProgress"><span>' + fileName + ' / ' + fileSize +'</span></div><a href="#" onclick="upDelete(\''+id+'\')">Delete</a></div>';
    	};
    	reader.readAsDataURL(file);
    };
    Code:
    function upDelete(fid){
    	//var element = document.getElementById("file-"+fid);
    	//element.parentNode.removeChild(element);
    	var fq = fileQuery.indexOf({id: fid});
    	fileQuery.splice(fq, 1);
    	console.log(fq);
    	//console.log(fileQuery);
    }

  2. #2
    Join Date
    Dec 2012
    Posts
    98
    Instead of storing the objects in an array store them in an object, that way the keys are fixed.

    Code:
    var fileQuery = {
       0: {
          id: 0,
          data: "some data"
       },
       1: {
          id: 1,
          data: "some more data"
       }
    };
    You can remove items from the object using the delete command

    Code:
    delete fileQuery[0];

  3. #3
    Join Date
    Aug 2008
    Location
    Sweden
    Posts
    227
    array.indexOf returns the index of the object you specify as argument. When you say {id: fid} you're actually creating a new unique object at that very point. The result in this case is that indexOf always will return -1 (because it will never find the newly created object in the array).

    To find the index of the object you're looking for you should loop through the array manually and compare the id property of all elements to fid. array.indexOf won't work in this case.

    Edit: to clarify, indexOf does not compare the properties of objects in an array, but rather the references of the objects themselves.
    Last edited by ReFreezed; 01-25-2013 at 01:03 PM.
    New to web development or in need of a good reference? Check out the Mozilla Developer Network or W3Schools.

  4. #4
    Join Date
    Jan 2013
    Posts
    3

    Exclamation Full script

    I am going to include the whole script so that you can get a full idea of what I am working with. I am building everything so its not blocking a.k.a asynchronous.

    Code:
    /**********************************************************************
    Collect the files and send them to an array
    
    var fileQuery = new Array();
    
    Array layout : {file_id: file}
    
    Create asynchronous script to push files into array to prevent site blocking (see setupDisplay)
    
    ***********************************************************************/
    
    var dropBox;
    var fileBox;
    var files;
    var proc;
    var fileQuery = new Array();
    var allowedFileTypes = new Array("imgage/jpg", "image/jpeg");
    
    window.onload = function(){
    	dropBox = document.getElementById("dropBox");
    	dropBox.ondragenter = ignoreDrag;
    	dropBox.ondragover = ignoreDrag;
    	dropBox.ondrop = drop;
    	
    	proc = document.getElementById("proc");
    	fileBox = document.getElementById("files");
    	fileBox.onchange = fileSelected;
    };
    
    function ignoreDrag(e){
    	e.stopPropagation();
    	e.preventDefault();
    };
    
    function drop(e){
    	e.stopPropagation();
    	e.preventDefault();
    	proc.innerHTML = "";
    	proc.innerHTML = "Please wait while we process your images";
    	var data = e.dataTransfer;
    	files = data.files;
    	fileArray(files);
    };
    
    function fileSelected(){
    	files = document.getElementById('files').files;
    	fileArray(files);
    };
    
    function fileArray(files){
    	var counter = 0;
    	var len = (files.length - 1);
    	function asynFor(){
    		if((counter <= len)){
    			var file_id = counter;
    			var file_data = files[counter];
    			//console.log(file_data.type);
    			fileQuery.push({id: file_id, data: file_data});
    			counter++;
    			setTimeout(asynFor, 1);
    		}
    		if(len == counter){
    			setupDisplay(fileQuery);
    		}
    	};
    	setTimeout(asynFor, 1);
    };
    
    function showArray(){
    	console.log(fileQuery);
    }
    
    function setupDisplay(fileQuery){
    	var counter = 0;
    	var len = fileQuery.length;
    	function asynFor(){
    		if(counter <= len){
    			setupFileList(fileQuery[counter].data, counter);
    			counter++;
    		}
    		setTimeout(asynFor, 1);
    	};
    	setTimeout(asynFor, 1);
    };
    
    function upDelete(fid){
    	//var element = document.getElementById("file-"+fid);
    	//element.parentNode.removeChild(element);
    	var fq = fileQuery.indexOf({id: fid});
    	fileQuery.splice(fq, 1);
    	console.log(fq);
    	console.log(fileQuery);
    }
    
    function setupFileList(file,id){
    	var filelist = document.getElementById("filelist");
    	var fileName = file.name;
    	var fileSize = 0;
    	var reader = new FileReader();
    	reader.onload = function(e){
    		var imgsrc = e.target.result;
    		if(file){
    			if(file.size > 1024 * 1024)
    				fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + "MB";
    			else
    				fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
    		}
    		
    		filelist.innerHTML += '<div id="file-'+id+'" class="upFiles"><img class="upImg" src="' + imgsrc +'" width="50px" height="50px"><div class="upProgress"><span>' + fileName + ' / ' + fileSize +'</span></div><a href="#" onclick="upDelete(\''+id+'\')">Delete</a></div>';
    	};
    	reader.readAsDataURL(file);
    };
    
    function uploadFiles(files){
    	for(var i=0;i<files.length;i++){
    		var xhr = new XMLHttpRequest();
    		var uploadForm = new FormData();
    		uploadForm.append("html_file", files[i]);
    		xhr.addEventListener("loadstart", uploadSetup, false);
    		xhr.upload.addEventListener("progress", uploadProgress, false);
    		xhr.addEventListener("load", uploadComplete, false);
    		xhr.addEventListener("error", uploadFailed, false);
    		xhr.addEventListener("abort", uploadCanceled, false);
    		xhr.open("POST", "uploader.php");
    		xhr.send(uploadForm);
    	}
    };
    
    function uploadProgress(e){
    	if(e.lengthComputable){
    		var precentComplete = Math.round(e.loaded * 100 / e.total);
    		//
    	} else {
    		//
    	}
    };

  5. #5
    Join Date
    Jan 2013
    Posts
    3

    resolved Thanks

    iBeZi thanks. Rewrote the code using your example and works just how I want.

    Quote Originally Posted by iBeZi View Post
    Instead of storing the objects in an array store them in an object, that way the keys are fixed.

    Code:
    var fileQuery = {
       0: {
          id: 0,
          data: "some data"
       },
       1: {
          id: 1,
          data: "some more data"
       }
    };
    You can remove items from the object using the delete command

    Code:
    delete fileQuery[0];

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles