In the event that the name and operator match, the recent value will be updated, but this functionality does not apply during the second

My application involves an array of filters containing the name, operator, and value:

[{name="pricing.price", op="gte", value=10000}, {name="pricing.price", op="gte", value=10000}]

After applying these filters and refreshing the page, the last set of filters is saved in this.savedFilters. Users can then add new filters or modify existing ones.

Adding new filters works perfectly, but modifying existing filters does not function as expected.

I have created a function that partially fulfills the job. It updates the value once when first run, but subsequent updates do not affect anything.

You can view the issue on JSFiddle: https://jsfiddle.net/cdr8btwe/

//if there are no saved filters, the new filters are the final filters
if (!this.savedFilters) {
          this.finalFilters = this.freshFilters;
        } else {

//concat the new & saved filters & move into a temp array

          this.tempArrayOfFilters =
            this.freshFilters.concat(this.savedFilters);

//forEach loop to check

          this.tempArrayOfFilters.forEach((value) => {
            const key = value['name'] + '_ ' + value['op'];

            if (this.mapping[key]) {
            } else {
              this.finalFilters.push(value);
              this.mapping[key] = true;
            }

          });
        }

        console.log('finalFilters:', this.finalFilters);
[
{name:"pricing.price",op:"gte",value:1234}, {name:"pricing.price",op:"lte",value:1111}
]

When attempting to modify saved filters with:

this.freshfilters = [{"name":"pricing.price","op":"gte","value":5678},
{"name":"pricing.price","op":"gte","value":9999}]

The output currently shows:

[{name:"pricing.price", op:"gte", value:1234},
{name:"pricing.price", op:"lte", value:1111}]

However, the desired output should be:

[{name:"pricing.price",op:"gte",value:5678},{name:"pricing.price",op:"lte",value:9999}]

This is because if the name and operator are the same, only the value should be updated.

Answer №1

If you're not sure what you're attempting to achieve, give this a try. It might provide some assistance.

    let arr1 = [{name: "pricing.price", op:"gte", value:1234}];
    let arr2 = [{name: "pricing.price", op:"gte", value:5678}];
    let arr3 = [{name: "pricing.price", op:"lte", value:1111}];
    let arr5 = [{name: "pricing.price", op:"lte", value:9999}];

    let arr4 = []

    arr4 = arr4.concat(arr1, arr2, arr3, arr5);


    final_arr = []
    mapping = {} // truthy mapping of name and p.p

    arr4.forEach((value) => {
    key = value["name"]+'_ '+value["op"]
    final_arr[key] = value;

     //if (mapping[ key ]) {
    //} else {
    //final_arr.push(value)
    mapping[key] = true
    //}

    })

    //Current Output

    /* 
    [
    {name:"pricing.price", op:"gte", value:1234},
    {name:"pricing.price", op:"lte", value:1111}
    ]
    */


    //Expected Output

    /* 
    [
    {"name":"pricing.price","op":"gte","value":5678},
    {"name":"pricing.price","op":"lte","value":9999}
    ]
    */


    console.log('final_arr: ', final_arr)

Link to the JSFiddle for more details

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

Loading CSS files from the Assets folder in Angular 2/4: Step-by-step guide

I have a question regarding my .angular-cli.json file configuration. Here is what I have defined: "styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/assets/css/main.css", "styles.css" ], In my assets folder, I have CSS files loca ...

Display toastR when the form is submitted by clicking on it

As a practice, I am developing a simple PHP shop and I want to enhance its functionality by showing a ToastR notification when the submit button is clicked with the message "Product successfully added to cart". However, being new to PHP, I am facing an iss ...

Developing a C program to initialize an array with user-defined length

Looking to experiment with an array of variable length for generating a string. The goal is to count words and adjust the array size accordingly. This is just a test, so I'm sharing it here to gather feedback on whether this approach is sound or flawe ...

Something is seriously wrong with the datetime in fullcalendar JavaScript

I've been diving into a tutorial for creating a calendar scheduler in asp.net MVC5 from this link. One issue I'm facing is the datetime being passed and stored as the min value in the database (1/1/0001 12:00:00 AM), almost like it's null b ...

Flipping a matrix in C using one-dimensional arrays

There is a matrix represented by a one-dimensional array: For instance, the matrix displayed as: 0 1 2 3 4 5 6 7 8 9 10 11 Corresponds to an array: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 I need to determine the dimensions of this matrix and t ...

Unique hover tags such as those provided by Thinglink

Looking for a way to replicate the functionality of Thinglink? Imagine a dot on an image that, when hovered over, displays a text box - that's what I'm trying to achieve. I thought about using tooltips in Bootstrap, but I'm not sure if it ...

Why is my HTTP request callback not being executed?

I've been trying to send an HTTP POST request to a 3rd-party API using a promise method. Oddly enough, the callback function never seems to run, even though when I test the code on its own, the API call is successful. Node.js and the concept of an e ...

Is anyone else experiencing issues with loading a font from a CDN? It works perfectly fine on Chrome Browser and Safari for iOS Simulator, but for some reason, it's not loading

It's driving me a bit crazy as I'm not sure where I've gone wrong. I'm currently working with NextJS and have loaded this font into my <Link />. While it displays perfectly on Chrome and Safari in the iOS simulator, it fails to l ...

Webster Barron code script

I'm attempting to replicate the concept of this video https://www.superhi.com/video/barron-webster using text, but I am encountering difficulties in achieving the desired effect. The design text is currently overlapping my name and displaying in rev ...

Retrieve the response text from a jQuery.get() call and return it

Attempting to achieve the following: var msg = $.get("my_script.php"); Expecting msg to be assigned to the text returned by my_script.php, which should be the responseText of the jqXHR object. However, it seems that msg is consistently set to "[object XM ...

Step-by-step guide to rapidly resolve all issues in VS Code using TypeScript

After extensive searching in VS code, I have not been able to find a quick fix all solution in the documentation or plugins. Is this feature actually non-existent, or is it possible that I am overlooking a keybinding? (I am currently utilizing typescript s ...

How can I verify if a user is logged in using express.Router middleware?

Is there a way to incorporate the isLoggedIn function as a condition in a get request using router.route? const controller = require('./controller'); const Router = require('express').Router; const router = new Router(); function isLo ...

Guide to displaying a standard view in Vue.js 3

I am attempting to display a default view/route immediately upon Vue.js loading. Currently, the page loads with the header and footer visible, but there is a brief delay before the homepage content is displayed. This results in the footer moving up to meet ...

populating the frame buffer with a square

I am struggling to generate an ASCII art square using an unsigned character array and display it on the screen. Here is the code snippet I have so far: #include <stdio.h> #define W 80 #define H 23 static int clear(unsigned char *p, int lim) { ...

Encountering CORS policy block when attempting to post data using Geoserver API through Angular

I'm currently working on Angular and I need to integrate the Geoserver API to publish spatial database data. Previously, I successfully used PHP Curl with the API and now I want to incorporate it into my Angular app. It's worth mentioning that ...

Progress bar powered by Ajax to enhance Django file uploads

As a newcomer to Django and JavaScript, I have a question about file uploading on my website. The situation is as follows: 1) My site has a file upload feature built in Django with the following logic: def page_query(request): ... if request.meth ...

Passing a variable to a cloned template in Angular 2: A guide

When working with Angular2, I encountered an issue with my template code that I am cloning every time a user clicks a button. Despite following instructions provided in this post How to dynamically add a cloned node in angular2 (equivalent to cloneNode), I ...

Unraveling a Map Object via an HTTP Request in Angular

I'm facing a puzzling issue. When I was using Angular 9.1, I had no problem sending a Map<string, string[]> through a request. However, after upgrading to Angular 13, this feature suddenly stopped working. Strangely, I couldn't find any inf ...

The AJAX error message shows that the function checkUsn is not defined when an HTMLInputElement.onkeyup

I'm currently developing a login form that is connected to a MySQL database and I'm trying to implement a feature where I can check if a username exists in the database without having to reload the entire page. I'm utilizing Ajax to send and ...

How can I efficiently locate identical sequences of cells in two or more arrays?

Unique Example 1 We can explore an interesting scenario by considering two arrays: ('m','o','o','n','s','t','a','r','d') ('s','t','a', ...