"Using JavaScript to find and manipulate objects within an array by either removing them or adding

I'm struggling to manipulate an array by either removing or adding an object based on its existence. I've attempted using both a for if loop and forEach loop but haven't been successful. Here's my current approach:

        // Object in store that needs modification
        this.sorts = [
          { field: "title", direction: "asc" },
          { field: "value", direction: "asc" }, // Remove if it exists, add if not
          { field: "quality", direction: "asc" },
        ];

        <button @click="handleCheckbox('value', 'asc')">Value</button>; // Example

        handleCheckbox(field, dir) {
        this.sorts.forEach((field, i) => {
          if (this.sorts[i].field === field) {
            this.sorts = this.sorts.splice(i, 1); // Remove the field if found in the array
            console.log("deleted=", this.sorts[i]);
            return;
          } else {
            this.sorts.push({ field: field, direction: dir }); // Add the field if it's not found
            console.log("pushed=", this.sorts[i]);
            return;
          }
        });
        // state.commit("setSorts", this.sorts);
        }

Answer №1

If you're looking to dynamically add an object to an array based on a specific condition, one approach is to use the findIndex method and then push the object into the array accordingly.

var arr = [
  { field: "title", direction: "asc" },
  { field: "value", direction: "asc" }, // remove if exists, add if not
  { field: "quality", direction: "asc" },
];

function findObject(obj, value) {
  var index = arr.findIndex(function(item) {
    if (item.field === value) {
      return true;
    }
  });

  if (index === -1) { 
    arr.push(obj);
  }
}

findObject({ field: "value", direction: "asc" }, 'value');

Answer №2

To find the index of an object based on a specified field and perform either push or splice operation depending on the index, you can utilize the findIndex method in JavaScript. Here is an example implementation using pure vanillaJS:

var items = [
          { category: "fruit", quantity: 10 },
          { category: "vegetable", quantity: 5 },
          { category: "grain", quantity: 3 },
        ];

function manageItem(category, newQuantity) {
  var index = items.findIndex(function(item){
    item.category == category
    // Example test outputs: console.log(item.category, category)
  });
    // Example test outputs: console.log(index)
  if (index < 0) { 
    items.push({ category, quantity: newQuantity });
  } else {
     items.splice(index, 1);
    }
}

Answer №3

Give this a try:

let sorts = [
    { field: "title", direction: "asc" },
    { field: "value", direction: "asc" },
    { field: "quality", direction: "asc" },
];

function handleChecklist(field, direction) {
    let index = sorts.findIndex(sort => sort.field == field);

    if (index === -1) {
        sorts.push({ field: field, direction: direction });
        return;
    }

    sorts.splice(index, 1);
}

handleChecklist("value", "asc");
console.log(sorts); // sorts = [ { field: "title", direction: "asc" }, { field: "quality", direction: "asc" } ];

handleChecklist("new", "asc");
console.log(sorts); // sorts = [ { field: "title", direction: "asc" }, { field: "quality", direction: "asc" }, { field: "new", direction: "asc" } ];

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

Utilize querySelectorAll to inspect class properties

When exporting a table to CSV, I have implemented the following logic: var cols = rows[i].querySelectorAll("td, th"); While this method works well, users are able to hide/display columns as they desire. Since AngularJS is used, the hidden columns are mar ...

Identify and handle multiple scenarios in JavaScript without using if statements

I have developed a function that is supposed to evaluate all scenarios and provide an immediate result if one of the cases does not match. const addText = (data, addAlternative) => { return (data !== 'N/T' || data === 0 || data) ? d ...

What is the best way to merge angularjs modules?

In my angularjs application using the codeigniter PHP framework, I have implemented 3 modules - cars.js for car details, cellphones.js for cellphone details, and home.js for home details. Each module caters to a different client's needs. I am trying ...

Using PHP to send variables to an AJAX function via parameters

I've encountered an issue while attempting to pass 4 variables through the parameters of the ajax function. The variables I'm trying to pass include the URL, action, ID, and timeout in milliseconds. Unfortunately, the function is not accepting th ...

Updating state in React with a nested promise within the useEffect hook

Trying to update the component state using React.useState with the help of useEffect. The reason behind using useEffect is that the API call response (EmployeeState > init()) determines what gets displayed on the UI. Component: import { EmployeeState } ...

Adding elements to an array in Vue.js using a method

I'm facing a puzzling issue that has left me perplexed My registration form activates a method on blur for every input field; <input class='form-control' placeholder='Username' @blur="watchVal" v-model="username"> The Meth ...

Using TypeScript with Watermelondb

I'm currently developing a React App and I want to implement Watermelondb for Offline Storage, but I'm unsure about using it with TypeScript. I have already set up the database and created Course and Lesson model files from the Watermelondb libra ...

Unexpected Error: Null value prevents accessing 'getElementsByClassName' property in HTML, along with Troubleshooting Inactive Button Behavior in HTML

Can someone identify the error in my HTML code? I keep getting an "Uncaught TypeError: Cannot read property 'getElementsByClassName' of null" error on the second line of the script tag. Additionally, my implemented active header code is not funct ...

Determine the variance between the final two items in an array composed of objects

I am trying to figure out how to calculate the difference in total income between the last two months based on their IDs. It seems that {income[1]?.total} always gives me a constant value of 900. Any suggestions on how I can accurately calculate the tota ...

Issue - Following error occurred in the file connection.js located in node_modules/mysql2 library: Module not found: Unable to locate 'tls' module

I've encountered an error in our Next JS applications where tls is not found. I have tried several troubleshooting steps including: 1. Updating Node modules 2. Using both mysql and mysql2 3. Running npm cache clean --force 4. Removing node_modules di ...

Symfony: The Database Query Button with a Pop-up Feature

I am looking to create a button that will automatically search my database for all users with a "secouriste" attribute set and display their first name, last name, and phone number in a popup. After conducting research, here is what I have gathered: In m ...

Determine the latest date within each group and display the corresponding output value

I am seeking a way to showcase only the most recent value for each group. For example, in the CSV data provided below, the total amount of Bagels in the Cinnamon Raisin variety were collected during three different sampling periods: May 2017, March 2017, ...

Looking to attach a listener to an element within a modal once it has finished rendering?

Upon clicking a button, a modal window appears. The controller assigned to the modal contains a list of element IDs that need listeners assigned. However, when the controller initializes, the modal has not yet rendered, causing the elements requiring liste ...

Can someone please help me figure out how to detect active users within my Next.js application while utilizing Supabase authentication?

I'm looking for a way to recognize users on my app in order to display green badges as visual cues. After logging into my app using Google OAuth, the session remains active even though I logged out days ago. I am unsure of the most effective algorith ...

Fetch several images simultaneously from a photo collection using JavaScript by generating a batch process

I need help with creating an image gallery that allows users to download multiple images by selecting them. The download should result in a zip file. I have checkboxes for selecting the images, but I'm struggling to figure out how to enable the downlo ...

Iterate over a JSON object to calculate the total sum of values based on distinct nested properties

Here is a JSON object that contains cost and author information. I am working on this in Express.js and using Underscore. [ { "Cost": 250, "author": { "id": "2", "name": "Joe", "workId": "5" } }, { ...

Having trouble with React's conditional rendering not working as expected?

I am currently working on updating the contents of my Navbar and Router by using useContext and conditional rendering techniques. Here is a snippet from my App.js: import "./App.css"; import axios from "axios"; import { AuthContextProv ...

Is it possible for a jQuery selector to retain its object? What can be done to prevent it

One interesting scenario involves a dropdown element within a container. <div class='container' /> <script> var dropdown = "<select class='multi-dropdown'> ... </select>" </script> Every time the value ...

Creating a Javascript map that holds an array of strings as values, mirroring the functionality found in Java

Seeking guidance on implementing HashMap functionality in JavaScript. Discovered the map() global object introduced in ES6 for this purpose. However, encountering issues when attempting to set a value as an array. Any help would be appreciated. Map-JavaS ...

AngularJS $scope variable can be initialized only once using an HTTP GET request

I'm facing an issue with fetching data from an API in a separate AngularJS application. There's a button that triggers the retrieval of data from the API. Upon clicking, it executes the $scope.getApiData function, which is connected to $scope.pr ...