Attempting to verify the presence of an element within an array and then making updates to the array

My current goal is to create a function called toggleStar, which will allow users to select an item from a list of JSON objects and add it to another list, known as the Favorite list.

I attempted to use indexOf in my code, but it doesn't seem to be functioning as expected. Any suggestions or help would be greatly appreciated!

Thank you in advance!

$scope.favlist = JSON.parse($window.localStorage.getItem("favlist"));
    console.log($scope.favlist);

$scope.toggleStar = function(item) {
      item.star = !item.star;
      console.log(item);

         var favlistcontent = $window.localStorage.getItem("favlist");
         if(typeof favlistcontent !== 'string'){
           $scope.favlist = [];
           $window.localStorage.setItem("favlist",JSON.stringify($scope.favlist));
         }
         $scope.favlist = JSON.parse($window.localStorage.getItem("favlist"));
         if( $scope.favlist.indexOf(item) === -1 ) {
         $scope.favlist.push(item);
         $window.localStorage.setItem("favlist",JSON.stringify($scope.favlist));

       } else if( $scope.favlist.indexOf(item) > -1 ){
        console.log("item already exist");

      }

  }

Answer №1

indexOf() function will only return a valid result if the array contains the exact same object reference.

In cases where the array has just been created from a JSON string, the objects it contains may not have the same reference as the one you are searching for.

To find the item that matches your criteria, you will need to loop through the array and compare IDs or other unique identifiers.

For instance:

var arr = [{foo: "bar"}];
var b = {foo: "bar"};

arr.indexOf(b); // This will return -1 since they are different object references

Another example:

var arr2 = [];
var x = {foo: "bar"};

arr.push(x);
arr.indexOf(x); // This will give 0 as a result because it is the same object reference

Additionally, you can utilize angular.equals() method to verify the match during iteration, but be sure not to modify item.star until after completing the comparison.

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

Version 4.6.4 of TypeScript is flagging the code as invalid

How can I fix this Typescript problem? const userInformation: { email: string; id: string; _token: string; _tokenExpirationDate: string; } = JSON.parse(localStorage.getItem('userData')); https://i.sstatic.net/xMh9P.pn ...

The navigation bar created with HTML, CSS, and JS is not displaying the menu as expected and is also experiencing issues with changing the order of links

I'm currently in the process of revamping my portfolio site, opting to use Bootstrap for the layout due to its efficiency. While attempting to implement a drop-down navbar using Bootstrap, I encountered difficulties as the menu failed to appear. Thus, ...

Velocity.js causing a slowdown in animated performance

Currently, I am attempting to animate spans, and while the animation is functional, it appears to be somewhat choppy and lacks smoothness. https://codepen.io/pokepim/pen/JBRoay My assumption is that this is due to my use of left/right for animation purpos ...

Firebase Error: In order to deploy without hosting via source, options must be provided. (app/no-options)

After developing a Next.js application, I integrated Firebase authentication and utilized the useContext hook for managing user state throughout the app. Here's the snippet of code for the AuthContext: auth.js import { createContext, useState, useEff ...

Creating a webpage that dynamically loads both content and video using HTML and Javascript

I designed a loading page for my website, but I could use some assistance. The loading page remains visible until the entire HTML content is loaded and then it fades out. However, I am facing an issue because I have a background video that I want to load ...

Empty req.body in Node.js when POST method is used

I'm completely new to exploring REST and Express, and I've been following this insightful tutorial on creating a REST API. Here's a glimpse of my programming journey through the lens of my app.js code: var express = require('express&ap ...

Importing files dynamically in JavaScript

Currently, I have a requirement to dynamically import a markup file, extract a portion of the file, assign it to a variable, and then display the result in my React application: import('../changelog.md').then(...) I have attempted to achieve th ...

several ngGrids and ngGridEventScroll

There are 2 separate ng grids on a single page, each with infinite scrolling that loads server-side data on ngGridEventScroll. scope.$on('ngGridEventScroll', function(event) { ... }); Each grid is designed to make its own unique server-side cal ...

Having difficulty linking the Jquery Deferred object with the Jquery 1.9.1 promise

I have been developing a framework that can add validation logic at runtime. This logic can include synchronous, asynchronous, Ajax calls, and timeouts. Below is the JavaScript code snippet: var Module = { Igniter: function (sender) { var getI ...

Retrieve specific information from a JSON file and save it in an array using Node.js/JavaScript

My goal is to extract all log details from a JSON object, but the issue is that the key for each user is constantly changing. let userJsonObject = { "user_1":{ "id":"user_1", "log":"de-data", ...

Guide to making control bar fade out when video is paused on video.js

Is there a way for the control bar to automatically disappear when the video is paused? Thank you in advance! ...

One-liner for converting an array into an object

Is there a more concise method to convert all array indices and values into an object than the following: arr = ["one","two","three"]; var rv = {}; for (var i = 0; i < arr.length; i++) rv[i] = arr[i]; I understand that you can iterate through the ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

Ways to send data to nested elements when implementing secure routes?

I am currently working on a project to develop a 'Train Ticket Reservation System' using ReactJS. In order to access the services, users must login, so I have implemented protected routes to render certain components. Instead of relying on the de ...

Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected. Here's the content of my HTML page: <!doctype html> <htm ...

What is the best way to load images into dynamically generated divs?

I recently wrote a code snippet that dynamically creates divs based on the number of text files found in a local directory. However, I encountered an issue while trying to add code to append photos to each of these created divs. Unfortunately, the photos ...

Toggle the visibility of images with input radio buttons

Explanation I am attempting to display an image and hide the others based on a radio input selection. It works without using label, but when I add label, it does not work properly. The issue may be with eq($(this).index()) as it ends up selecting a differ ...

Converting PHP Unicode character faces to hexadecimal for Arabic characters

I'm having trouble converting Arabic characters to hexadecimal values. $text = "يي"; $text = mb_convert_encoding($text, "HTML-ENTITIES", "UTF-8"); $text = preg_replace('~^(&([a-zA-Z0-9]);)~',htmlentities('${1}'),$text) ...

Use jQuery to modify the default yellow color of Chrome's autofill feature

Struggling to get this code to work on my website, and it's starting to drive me crazy. I followed the instructions from BenjaminMiles' website, but something just isn't clicking. The jquery code snippet I'm using is: <script> ...

Exploring a Collection in Meteor: Working with an Object

This issue has been plaguing me for some time now, and it's starting to really get on my nerves. To put it simply: How can we iterate over an object within a collection in a template? Each entry in the collection typically looks like this: { "_i ...