Verifying conditions within an array of objects in JavaScript

Verify an array of objects based on certain conditions. The array of objects starts off empty.

1. If the array is empty and an action occurs, add an object to the array.

2. If the array already contains an object, check if it already exists. If it does, delete the object from the array. If it doesn't, add it to the array.

I've attempted the following code:

  var arr = [];
    $(document).ready(function() {
        $(".rating").click(function() {
            var idx = $(this).closest('td').index();

            var userskill = {
                tech : $(this).closest('td').siblings('td.tech').text(),
                skill : $('#listTable thead th').eq(idx).text(),
                rValue : $(this).val()

            }
            add(userskill);
        });

    });

function add(userskill) {
    var flag = false;
    arr.push(userskill);
    for(var i in arr){
        if((arr[i].tech==userskill.tech)&&&(arr[i].skill==userskill.skill)){
            arr.splice(i, 1);
        }

    }

Answer №1

If you're looking for a solution to your problem, you might find Underscore.js interesting. For example, the isEqual method can be used for object comparison.

Edit:

Here is a code snippet using _.findWhere:

function add(userskill) {
  if(!_.findWhere(arr, userskill)) {
      arr.push(userskill);
  }
}

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

JavaScript threw an error with message: 'Unexpected identifier' that was not caught

Upon launching Web Developer in Firefox: SyntaxError: missing } after property list note: { was opened at line 7, column 7 ...

How to customize the preview grid design in material-ui-dropzone

I am working on a book form page in my React app which includes an option to upload a cover photo. I opted for material-ui-dropzone from https://yuvaleros.github.io/material-ui-dropzone/ and it's working well, but I encountered an issue with the previ ...

What is the process for inserting an array into a datagridview?

Hey there, I'm facing an issue where I need to place an array into a DataGridView. The code I have only gives me the positions of the array in the rows, but the rows themselves are empty... Could someone lend a hand with this? int[] arrays = new in ...

Determining the Index Positions of Array Elements

After analyzing the code provided, I have come up with a way to optimize it. The goal is to rewrite the code using a simple array data structure instead of the List data structure. Let's start with the method computeLanguage(char[], int): private stat ...

The Parse.com cloudcode refuses to enter the success or error state

Running this code in my Parse cloud, I noticed that when I call it from my app, it never enters the success or error statement. Could it be because the .save method isn't working? Any assistance would be greatly appreciated :) This is how I invoke t ...

Having trouble importing the module I developed in Node

I've been struggling to understand why this import is failing. Despite trying numerous approaches, modifying the export and import based on various tutorials online, it continues to result in failure every time. This should be a simple task in theory. ...

Session management functions properly in Postman, however, encountering issues when attempting to use it on a web

Working on a NodeJS project using express-session to handle sessions. When sending a post request to http://localhost:5500/login, a session is created with an additional property userid. Upon making a get request to http://localhost:5500/ using Postman, th ...

Having trouble with React JS BrowserRouter not routing correctly when used with Express JS and Nginx proxy

I am facing an issue where I need to send parameters to a React component through the URL. This works perfectly fine when I test it in my localhost development environment. However, the problem arises when I deploy the React app to my live server (). The ...

Having trouble converting a timestamp to a date in JavaScript

My database uses MongoDB and has a timestamp field with unique formats, such as: 1657479170.7300725 1657479170.7301126 1657479170.7301197 1657479170.9120467 1657479170.932398 Converting these timestamps to the date format YYYY-MM-DD yields the correct res ...

Automatically submitting an HTML form from a JSP page

Encountering the same origin policy issue with Ajax, but in need of sending a form post to a different server. The question at hand is: How can I call my JSP to automatically submit a form to another server? Attempts to use an AJAX call to the JSP page h ...

The draggable=true attribute in EaselJS (MovieClip) canvas does not display a ghost image

I am currently working with a canvas element that contains animations powered by EaselJS. The canvas is wrapped in a parent div with draggable set to true. <div class="outer-parent" draggable="true"> <div class="inner-parent"> <canvas& ...

Leveraging the push method within AngularJS

Hello, I am currently working on setting up an eCommerce shop using Angular. Below is the code snippet I am using: var shopApp = angular.module('shopApp', ["slugifier"], function() {}); controllers.productController = function($scope,FetchFa ...

Analyzing the HTTP status codes of various websites

This particular element is designed to fetch and display the HTTP status code for various websites using data from a file called data.json. Currently, all sites are shown as "Live" even though the second site does not exist and should ideally display statu ...

Is it possible to incorporate a React app as a component within a static HTML page?

Looking to integrate the react-csv-viewer component into a static HTML page without deploying it on a local server. I've tried following the instructions from the React tutorial, but am struggling with the build process. My goal is simple - to use th ...

Modifying paragraph content with JavaScript based on selected radio button values and troubleshooting the onclick event not triggering

I am working on implementing a language selection feature on my website where users can choose between English and Spanish. The idea is to have two radio buttons, one for each language, and a button. When the button is clicked, the text of the paragraphs s ...

storing the output from a MySQL array into a PHP variable

My goal is to send SMS to all the members listed in a MySQL table using an API. Currently, I am only able to send the SMS to the first row in the table. However, my intention is to send the message to all records in the table. The code snippet I am using ...

What sets React$Element apart from ReactElement?

Attempting to implement flow with ReactJS and needing to specify types for prop children. The article on Flow + React does not provide any information. Despite encountering examples using ReactElement (e.g), I received an error message from flow stating i ...

Ways to adjust your selection to the space or new line before or after

$('button').on('click', function(){ const selection = window.getSelection(); selection?.modify('move', 'backward', 'word'); selection?.modify('extend', 'forward', 'to the next space ...

How can I retain the selected item's information from a list in React JS when navigating to the next page?

In order to showcase various countries, I utilized ListItem in my Country.js file. For a visual representation of this setup, check out the CodeSandbox link I have provided: My Code One functionality I am aiming for is having the program remember the sel ...

Difficulty with info window within a for loop

I am currently working on implementing multiple info windows for markers. I found an example on Stack Overflow that I am trying to follow. Despite not encountering any errors in the console, the info windows do not appear as expected when clicking on the m ...