Challenges with identifying the key and value in Javascript Arrays using indexOf

Within a certain key, I am storing an array with values in this format:

{id: 0, data: mydata}

Additionally, there is a corresponding list for each ID, used for file deletion and element removal.
The issue arises when attempting to delete an object from the array using the JavaScript splice function, as it alters the index values.

Refer to the JavaScript code snippet 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);
}

Answer №1

Instead of using an array, consider storing the objects in an object to ensure fixed keys.

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

To remove items from the object, use the delete command.
For example:

delete fileQuery[0];

It's important to note that indexOf does not compare properties of objects within an array, but rather the references of the objects themselves. When using array.indexOf, it will return the index of the object passed as an argument, creating a new unique object at that point. Therefore, indexOf will always return -1 because it won't find the newly created object in the array.

To find the index of the object you're looking for, loop through the array manually and compare the id property of all elements with the desired id. In this case, array.indexOf won't be effective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method to remove duplicate watches in AngularJS?

After creating a basic TODO app using AngularJS, I discovered some interesting features. https://i.sstatic.net/QHfdy.png The app allows me to manage my list of tasks, such as deleting, marking as completed, and adding new ones. A unique functionality is ...

Ways to transmit information among Vue components

I am trying to figure out how to pass data from the Module variable in CoreMods.vue to ExternalWebpage.vue using Vuex. I want the CoreModule state to be watched for changes in the external webpage. This is my store.js setup: import Vue from 'vue ...

Using JQuery to append an additional column to an HTML table at the end, determined by array information

I've been experimenting with how to enhance an html table by adding a new column of data. The process involves clicking a button, extracting the existing data column in the table, storing it in an array, performing calculations on it, and then display ...

Tips for Choosing the Right Objects in Vue.js

I have the following code that combines all objects in a person and stores them in an array called Cash:[] this.cash = person.userinvoice.concat(person.usercashfloat) Inside person.usercashfloat, there is an element called validate which sometimes equals ...

Troubleshooting a jQuery Selector Issue with a Dynamic Form

I developed a jQuery function to search for all the necessary inputs in a specific section of a website. function check_property_vars() { jQuery(this).parents('.property_group').find('div[id^="property_group_"]:input[required]:visible&a ...

Select three unique numbers at random from the total number of elements in the array

I currently possess an array containing a variety of objects. At present, there are 21 objects in this array, although this number is subject to change. To iterate through the array and generate the necessary content, I am implementing the following code ...

Combining First and Last Names for MongoDB Searches

Within my MongoDB database, I have stored two fields - FirstName and LastName. On the frontend, I am receiving a string that contains both the first name and last name separated by a space. I need a query to search for a match using both the first name and ...

Error: Express JS custom module cannot be located in the root directory's modules folder

The file structure of my express js app resembles thishttps://i.sstatic.net/57NIQ.png I'm attempting to load a modules folder from the root directory. routes/users.js var express = require('express'); var router = express.Router(); var md ...

The execution of Javascript should be limited to when the tab or browser window is in focus

Similar Question: Detect If Browser Tab Has Focus I have developed a basic Java applet that is capable of capturing a client's screen. By using a small piece of JavaScript code, I can initiate the applet and capture the active screen image. Howe ...

Leveraging Next.js ISR to pass extra information to the getStaticProps function from the getStaticPaths

Inside SingleBlogPost.jsx, the code for generating blog pages by their slug is as follows: export async function getStaticPaths() { const res = await fetch("http://localhost:1337/api/posts"); let { data } = await res.json(); const paths = data.map(( ...

The jspdf function is not displaying any images in the PDF file

I am new to coding and encountered an issue when trying to download images in reactjs. After clicking the download button, I only receive a blank pdf file. https://i.stack.imgur.com/0XJcC.png The function in my react code that attempts to generate the p ...

A Python approach to reading lines from a file and dividing them into separate parts

How can I start a for loop on a specific index in an array when splitting lines from a locally stored .txt file? For instance: file_content = open('files/filefinal1_test.txt') counter = 0 total_lines = 0 global l index = 0 if l == "" e ...

Ajax continues to repeatedly redirect to the PHP page

I currently have a Shopify store and I am looking to incorporate a form on the product page. However, I am facing an issue where when I try to submit the form using AJAX with an external link, it redirects to the external page instead of staying on the cur ...

When there is a lack of internet connection, WKWebView does not reach completion or timeout

When using a WKWebView to navigate to a local HTML page, I encountered an issue with a remote Javascript asset tag that never finished downloading. This occurred even when the iOS device was not connected to the internet or had slow internet speeds. The p ...

Message displaying successful AJAX response

I'm currently updating my AJAX request to make it asynchronous, but I am wondering if there is an equivalent to var response = $.ajax({ in the success function. Previously, my code looked like this: var response = $.ajax({ type : "GET ...

Create an interactive visualization using d3.js

Currently, I am on the hunt for a technology that can help me render a tree structure based on Json data. After researching options like graphViz and d3, it seems like d3 is more optimized for modern browsers. With the extracted Json data, my goal is to c ...

How come my fixed navigation bar is appearing above my sticky navigation bar even though I positioned it at the bottom in the code?

My current project involves creating a sticky bar and fixed navbar using Bootstrap 5. I structured my code with one file for the sticky navbar and another file for the fixed navbar. The challenge I faced was having the fixed navbar overlap the sticky navba ...

Is it possible to utilize the Node.JS PassThrough stream as a straightforward input buffer?

In my Node.js application, I am utilizing a subprocess referred to as the "generator" to produce data. The challenge arises when the generator occasionally outputs a large chunk of data at a speed of around 50MB/s, while generally operating at a much slowe ...

The presence of fs.existsSync as a function is not recognized when importing electron

I am currently developing a Vue and Electron application and I encountered a problem while trying to restart the application. Here is my code snippet: import { app } from 'electron'; export default { name: 'Home', methods: { re ...

Executing Enter Key and Button Simultaneously with JavaScript: Step-by-Step Guide

I need assistance understanding how to simultaneously trigger the enter key and button in this code. When the value is entered into the input field, it should trigger both the enter key and the button "Enter" at the same time. Additionally, after pressing ...