add to array object if it does not already exist

I am currently working with the following model in JavaScript and utilizing AngularJS:

$scope.data = {
            FocusOn: " ",
            Filters: [],
            Range: {
                From: "",
                To: ""
            }
        }

Additionally, I have the following function defined:

$scope.addField = function ($type, $value) {
            $scope.data1 = {
                FilterName: $type,
                FilterValue: $value
            };
            if ($scope.data.Filters[$type] === undefined) {
                $scope.data.Filters.push($scope.data1);
            }
            $scope.data1 = "";
            $scope.Json = angular.toJson($scope.data);

        };

I am trying to add items to the Filters array only if they are not already present. Can anyone provide assistance on how to achieve this?

I attempted the above approach but encountered issues. Any help would be greatly appreciated.

Thank you.

Answer №1

Assuming that $scope.data.Filters consists of an array of objects with properties like FilterName and FilterValue, it becomes necessary to search the array for a matching object before insertion. This involves comparing the values of the properties of the object, going beyond a mere shallow equality check as offered by indexOf().

If you have access to libraries such as lodash or underscore, the _.findWhere() method can simplify this task:

if (!_.findWhere($scope.data.Filters, $scope.data1)) {
    $scope.data.Filters.push($scope.data1);
}

Alternatively, you may create your own function. In this case, your complete code would look something like this:

$scope.addField = function ($type, $value) {
    $scope.data1 = {
        FilterName: $type,
        FilterValue: $value
    };
    if (!filterExists($type)) {
        $scope.data.Filters.push($scope.data1);
    }
    $scope.data1 = "";
    $scope.Json = angular.toJson($scope.data);
};

function filterExists(type) {
    for (var i = 0, len = $scope.data.Filters.length; i < len; i++) {
        if ($scope.data.Filters[i].FilterName === type)
            return true;
    }
    return false;
}

Answer №2

Give this a shot:

$scope.addFilter = function ($type, $value) {
        $scope.filterData = {
            FilterType: $type,
            FilterValue: $value
        };
        if ($scope.filters[$type] === undefined) {
            $scope.filters[$type] = $scope.filterData;
        }
        $scope.filterData = "";
        $scope.jsonData = angular.toJson($scope.filters);
    };

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

How to properly align TableHeader and TableBody contents in a Material-UI table

I am experiencing an issue with a file that is supposed to display a table of data pulled from a database. Although the table does appear, all the data seems to be displayed under the ISSUE NUMBER column, instead of being aligned with their respective col ...

Discovering a way to showcase every event a user is linked to, employing Fullcalendar Rails

Here is the current model structure: class User < ActiveRecord::Base has_and_belongs_to_many :event_series has_many :events, through: :event_series end class Event < ActiveRecord::Base belongs_to :event_series end class EventSeries < Activ ...

Is it possible to determine if the process for changing Three.js material has been successfully completed?

Is it possible to determine the completion of this process? material.map = new THREE.Texture( canvas ); material.map.needsUpdate = true; If not, sometimes the final result will be a black snapshot. var snapshotData = renderer.domElement.toDataURL(strMi ...

Submit a form using Ajax without having to reload the page

Seeking help for implementing an ajax form submission with four answer options to a question. The goal is to submit the form without reloading the page upon selecting an option. Below is the code I have been working on. Any suggestions or solutions are wel ...

Infusing JavaScript with vibrant images

I am currently facing an issue where I am trying to insert images with JavaScript attached to them. Oddly enough, it seems to work fine on Firefox but the images or icons do not display on Internet Explorer. This is how I have written the code: <a hre ...

What is the frequency of 'progressEvents' occurring while uploading files via ajax?

Having recently started using ajax uploading, I wanted to include a progress bar to display the uploading process. I implemented a registration function for progressEvent, but unfortunately, it only ran once. This means that my progress bar was not functi ...

Is there a way to make a NodeJS Transform stream produce multiple records for each input chunk?

Currently, I am working on a Transform stream that has the capability to receive an incoming stream of XML data and then emit a subset of that in the form of JavaScript objects. <item> <name>some name</name> <files> <fil ...

Is there a way to logout when the select event occurs using the key?

I am trying to figure out how to log out the key value when the select event is triggered. Specifically, I want to access the key={localState.id} within the <select></select> element in my HTML. This key value is crucial for a conditional stat ...

Is there a way to retrieve the same post from one controller and access it in another?

Hello, I am currently exploring the world of Full Stack web development and have stumbled upon a challenge. My tech stack includes mongodb, mongoose, node, and express. Within my project, I have implemented two controllers - one for user signup and anothe ...

A React component created in a class cannot effectively update its state when using a functional component to pass

I'm currently working on a React project that involves both a Class component and a Functional Component. In my Class component, I have a function that updates the name in its state. The issue arises when I try to pass this function as a property to t ...

Trouble accessing environment variables within a React application, specifically when using webpack's DefinePlugin in a Dockerfile

I can't figure out why console.log is printing undefined. The files Makefile, config.env, webpack.config.js, and package.json are all located in the root of my project. Makefile: docker-run: docker docker run -it --env-file config.env -p "80:80" ...

Place a vertical slider adjacent to an HTML element on either the left or right side

I'm struggling to bind a range slider to the left or right side of a canvas that displays video. Despite my efforts, CSS seems to be putting up a strong fight. I can handle issues like stretching and slider values, but attaching it to the canvas is pr ...

Encountering a no-loops/no-loops eslint error in node.js code while attempting to utilize the for and for-of loops

While working on my nodejs application, I have encountered an issue with es-lint giving linting errors for using 'for' and 'for-of' loops. The error message states error loops are not allowed no-loops/no-loops. Below is the snippet of c ...

I am having trouble connecting the local JSON file to the website

I'm working on a school project where I need to link a local JSON data file to an HTTP webpage to retrieve the data, but I'm having trouble getting the results. The code below is the JSON local code that I want to integrate into the webpage inste ...

Can Angular handle properties containing hyphens within them?

As I embark on creating my first complete Angular application, I encountered an interesting quirk. The model I am working with has a data structure that looks like this: { id: "12345", host: { name: "someHostServer", ip-addresses: ...

AngularJS case-insensitivity match not functioning as expected

I came across a discussion about AngularJS and the case sensitivity of base href in this thread. Despite following the advice to use version 1.1.5, I am still facing the same issue. Angular continues to return the error message. This is what I have been t ...

"Is it possible to keep an eye on two different events and take action once they both

I have a menu with different submenus for each list item, all utilizing the same background tag. Currently, when one submenu is open and I hover over another list item, the previous submenus hide and the new one opens. What I want is for the content to cha ...

Ways to identify local storage when a user visits the page for the first time using jQuery

As a beginner in the world of local storage in Jquery, I am looking to implement a feature on my Bootstrap 4 accordion. The desired functionality is as follows: If a user is visiting the page for the first time, all accordions should be open by default ...

The error occurred when trying to hydrate my custom stroke text component after the 14th attempt

I recently embarked on developing an app using Next 14, and I came across the need for text with a stroke. However, the CSS stroke feature was not behaving as expected, creating an inner stroke effect instead of an outer stroke. To address this, I devised ...

Guide on utilizing fragment shaders from glslsandbox.com

I'm interested in experimenting with ShaderMaterial from Three.js, but I am not familiar with the OpenGL Shading Language. When I try to use the fragment shader code from the website mentioned above, I encounter a number of errors. I'm unsure if ...