Ways to include and remove an item from a json array by utilizing events such as cursor.observeChanges

Using cursor.observeChange to notify UI when a record is added. The record type is:

{"ref":"100","status":"inprogress"}

An empty array is initialized:

var arr=[];

To check if the status is in progress and the ref does not exist in any object in arr[], push it to arr:

arr.push(obj);

If the status is complete and the ref already exists in arr[], then delete it from arr[]. Below is what has been attempted:

var arr = [];
function addObject(obj){
    if(!arr.some(function(el){return (el.ref === obj.ref)}))
    {
        arr.push(obj);
    }
    else if{
        arr.splice(el, 1);
    }

}
var cursor = TransactionDetails.find({});
cursor.observeChanges({
    added: function(id, object) {
        if (object.status == "incomplete") {   
            addObject(object);
            Notification.error("added");
        } 
        else if(object.status == "complete") {
            addObject(object);
            Notification.error("modified");

        }
   }

});

The above code is not working as expected. How can we add and delete based on these conditions? Any assistance would be appreciated. Thank you!

Answer №1

To remove an object from the array arr, you can utilize a function specifically designed for this task.

This method makes use of Array#findIndex

function eliminateObject(obj) {
    var index = arr.findIndex(o => o.ref === obj.ref);

    if (index !== -1) {
        arr.splice(index, 1);
    }
}

Alternatively, you can employ an ES5 solution involving Array#some

function eliminateObject(obj) {
    function getIndex(el, i) {
        if (el.ref === obj.ref) {
            index = i;
            return true;
        }
    }

    var index;

    if (arr.some(getIndex)) {
        arr.splice(index, 1);
    }
}

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

Check if the browser is not Google Chrome before running the code in JavaScript

Related Search: Finding a secure way to detect Google Chrome using Javascript? Using Javascript to identify Google Chrome and apply CSS changes Is there a JavaScript statement that can be used to execute code only when the user is not using Google ...

Incorporating user input into a form using NodeJS and Angular

I am currently facing an issue while trying to add a new entry using NodeJS with an Angular form. Every time I click on create, the data is not being inputted into the database. To address this, I included the angular.toJson function to convert the input i ...

Concerns regarding the efficiency of JavaScript (Odin Project, Etch-a-Sketch) are arising

Currently, I am delving into Javascript on the Odin Project, tackling the Etch-a-Sketch exercise. This involves creating a board where you can draw with your cursor. As part of the exercise, there's a requirement to add a resize button that allows use ...

JavaScript tile mapping not rendering

<html> <head> <title>TileMap</title> <style> #canvas { outline: 1px solid #000; } </style> </head> <body> <canvas id="canvas" height="1000" width="1000"></canvas> <scr ...

What is the process for creating a custom Javascript function that can seamlessly integrate with other Javascript libraries?

Is there a way to create a method that can be linked or chained to jQuery methods and other library methods? For example, consider the following code snippet: var Calculator = function(start) { var that = this; this.add = function(x) { start = start ...

Error encountered when attempting to convert a JSON object to a String using JSON.stringify(), due to a cyclic object value

I have a JSON object with the following structure: obj { name: "abc" , entriesList : "list of entry obj" , propertiesList : "list of properties obj" }; In this structure, an entry is also another object entry { info : "data obj" , ...

Could there be an issue with the couch-nano changesReader batching, or am I overlooking something important?

This particular issue is related to the changesReader API within the couchdb-nano library. Expected Outcome In theory, the code below should wait for 10 seconds before returning a batch of messages from the most recent position in the changes feed. For in ...

Ensuring the query is executed prior to rendering in Node JS

At times, the result may only include type data instead of product data due to a possible async problem. However, there are also instances where both types of data are present. My current setup includes Node JS, Express, and Mongoose. router.get('/& ...

The tab indicator in Material-UI fails to update when the back button is clicked

My code is currently functioning well: The tab indicator moves according to the URL of my tab. However, there is a peculiar issue that arises when the back button of the browser is pressed - the URL changes but the indicator remains on the same tab as befo ...

What is the best way to dynamically update or display unique CSS styles when a service is invoked or provides a response in AngularJS using JavaScript

Seeking to display a unique CSS style on my HTML FORM prior to invoking a service in my code and then reverting back after receiving the response. I have implemented the use of ng-class to dynamically add the class when the boolean activeload1 is set to tr ...

Implementing recursive functionality in a React component responsible for rendering a dynamic form

Hello to all members of the Stack Overflow community! Presently, I am in the process of creating a dynamic form that adapts based on the object provided, and it seems to handle various scenarios effectively. However, when dealing with a nested objec ...

Can components be designed in a way that includes elements such as buttons or text areas in the code, but allows for them to be excluded when the component is used?

I have a custom form component that I designed. Depending on certain cases, I want the form to display either a button or a text field instead of the input field as currently coded. function FormTypeOne(props) { return ( <form className={classes.f ...

What is the optimal approach: Extracting HTML from a jQuery response?

Just wondering how people handle this situation...if a user adds something to a list and, when it's done, triggers the following ajax code to update the .user-stream-list $.ajax({ url: "user-stream-list.php", success: function(data){ ...

Choose the initial element that has a unique label

Looking to create a custom CSS class that will apply a background color only to the first element with a specific tag... This is what I have so far: .blue p:first-of-type { background-color:#2E9AFE; } It works in this scenario: <div class="blue" ...

Tips for storing a GET response in a variable using ExpressJS and LocomotiveJS

I am currently navigating the world of NodeJS and have successfully developed an app using ExpressJS and LocomotiveJS framework. I am now faced with a challenge: how do I store a particular GET response in a variable within a controller? For instance: fil ...

Creating Awesome Icons in Kendo Grid with Code In this tutorial, we will learn how to programm

Looking to have a Kendo grid display a green fas-fa-clock icon if isActive is true, and a grey far-fa-clock icon if false. Clicking on the icon should toggle between true and false. Currently, the grid just shows the word true or false in the column. Cod ...

Incorporate a controller into another controller on the fly using AngularJS

Within my application, I utilize a wrapper controller to manage certain properties dynamically based on the presence of other-controllers nested within it. While everything functions perfectly when the other-controllers are static upon loading, issues aris ...

What is the best way to upload this HTML file to create my own visual representation?

Feeling a bit unsure about which way to go for this problem, I don't have many options at the moment. Lately, I've been diving into Deep Learning and I'm interested in experimenting with Stanford's CS231N's Convolutional Neural Ne ...

Why am I receiving undefined for req.user in passportjs?

After setting up passportJS with my node express app, I encountered an issue where the req.user is undefined when making a login/register request. I am not sure what went wrong or if I missed something in the configuration of passport js. In my setup, I us ...

Associate information from a modal to a knockout model

I am attempting to utilize a Twitter Bootstrap modal that opens a window containing an editable text area. Upon saving, the relevant data should be saved. The current code I have is as follows: HTML: <table class="display table table-striped"> ...