JavaScript: Eliminate specific value from sub-array within an array of objects by using a designated key

My data array structure is as follows:

{
  "filters": [
   
    {
      "filterProperty": "companyType",
      "filterValues": [
        "Private"
      ]
    },
    {
      "filterProperty": "city",
      "filterValues": [
        "Mumbai",
        "SanJose",
        "Shanghai"
      ]
    }
    
  ]
}

I have implemented filters on this array. Now, I am removing them one by one and making API calls with the remaining filters.

If I want to remove only "Mumbai" from the filter property "city", while keeping the rest of the filter values intact, how do I achieve this?

  "filters": [
   
    {
      "filterProperty": "companyType",
      "filterValues": [
        "Private"
      ]
    },
    {
      "filterProperty": "city",
      "filterValues": [
        "Mumbai",
        "SanJose",
        "Shanghai"
      ]
    }
    
  ]


let data = filters.splice(a=> a.filterProperty === 'city' && a.filterValues.filter(b => b !== "Mumbai"))

Answer №1

It seems like a combination of map and filter functions would work best here. Here's an example:

const data = { "filters": [ { "filterProperty": "companyType", "filterValues": [ "Private" ] }, { "filterProperty": "city", "filterValues": [ "Mumbai", "SanJose", "Shanghai" ] } ]};

const updatedFilters = data.filters.map(item => item.filterProperty === "city" ? (item.filterValues = item.filterValues.filter(value => value !== 'Mumbai'), item) : item );

console.log(updatedFilters);

Answer №2

Utilize the power of Array.reduce()

const criteria=[{category:"price",values:["$10","$20"]},{category:"color",values:["blue","red","green"]}];

let results = criteria.reduce((accumulator,current) => {
  if(current.category === "color"){
    current.values.splice(current.values.indexOf("red"), 1);
  }
  accumulator.push(current);
  return accumulator;
}, []);

console.log(results);

Answer №3

Utilize forEach and filter to create a new array of items without altering the original data.

const filterArray = (obj, prop, value) => {
  const newFilters = [];
  obj.filters.forEach(({ filterProperty, filterValues }) => {
    newFilters.push({
      filterProperty,
      filterValues: filterValues.filter((item) =>
        filterProperty === prop ? item != value : true
      ),
    });
  });
  return {
    filters: newFilters,
  };
};

const data = {
  filters: [
    {
      filterProperty: "companyType",
      filterValues: ["Private"],
    },
    {
      filterProperty: "city",
      filterValues: ["Mumbai", "SanJose", "Shanghai"],
    },
  ],
};

const prop = "city";
const value = "Mumbai";

console.log(filterArray(data, prop, value));

Here is a solution that involves using find and splice, but mutates the data:

const data = {
  filters: [
    {
      filterProperty: "companyType",
      filterValues: ["Private"],
    },
    {
      filterProperty: "city",
      filterValues: ["Mumbai", "SanJose", "Shanghai"],
    },
  ],
};

const prop = "city";
const value = "Mumbai";

const cityFilter = data.filters.find(({ filterProperty }) => filterProperty === prop);
if (cityFilter) {
  const index = cityFilter.filterValues.findIndex((item) => item === value);
  if (index > -1) {
    cityFilter.filterValues.splice(index, 1);
  }
}

console.log(data);

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

Using PHP to ascertain the requested dataType or responseType from the client

My ajax request is fairly simple: $.post('server.php',data, function (json) {console.log(json)},'json'); I have configured jQuery to expect json data based on the dataType setting. Question: Is the dataType parameter equivalent to re ...

Tips for arranging, categorizing, and separating the array in alphabetical order using Angular 2+

I am looking to organize the buttons' content alphabetically into groups A-H, I-Q, and R-Z. The code I'm using is in Angular2+. https://i.sstatic.net/pPCBO.png My array: this.dropdownList = [ { item_text: 'Organisation' }, ...

Executing operations on checkboxes on a webpage without access to model files

I am facing an issue with accessing the models file due to encryption in the software. Currently, my checkboxes are implemented using Ajax within a PHP query. Since it is Ajax-based, I am unable to manipulate actions through the URL. My goal is to extract ...

I am experiencing an issue with my jQuery loop code not functioning properly when using the .each method within the loop

I am struggling with the following code. <input type="text" name="1" class = "inp<?=$p?>"> <input type="text" name="2" class = "inp<?=$p?>"> <input type="text" name="3" class = "inp<?=$p?>"> <input type="text" na ...

Issue with jQuery: submit() function not behaving as expected when navigating back in history

Incorporating jQuery's submit() method in order to perform basic form verification prior to redirecting the user to the subsequent page. $(document).ready(function(){ $("form").submit(function() { // carry out form validation and set erro ...

Steps for adding a border to kendo grid row hover

One of my tasks involved creating a grid using Kendo, and I wanted to display borders on a grid row when the cursor hovers over it. I attempted the following code snippet: .k-grid > table > tbody > tr:hover, .k-grid-content > table > tbody ...

What is the process of adding files to my Svelte / Sapper server build using __sapper__?

Currently, I am working on integrating a server middleware called Parse into my sapper server configuration located in sapper-project/src/server.js. express().use('/api', const api = new ParseServer({ databaseURI: 'mongodb://localhost:27 ...

Sharing data with external domains and retrieving HTML output using JavaScript

When a browser sends a POST request and expects an HTML page result from JavaScript, problems arise if there is no Access-Control-Allow-Origin in the server response. Unfortunately, changing anything on the server side is not an option. If a human clicks ...

Adjusting the size of tables in raw JavaScript without altering their positioning

I am attempting to adjust the size of a th element without impacting the position of the next th in the row. Specifically, I want the width of the th to influence the width of the next th accordingly, rather than pushing it to the left. Below is the code ...

I'm having trouble with the onImageUpload and sendFile functions in the summernote image upload feature

I have recently implemented summernote version 0.8.12 into my project. Below is a snippet of my page containing summernote: <!DOCTYPE html> <html lang="en"><head> <meta charset="UTF-8> <title>bootstrap4</title> ...

Leverage the power of gRPC with Node.js and TypeScript for seamless

I'm trying to implement GRPC in a Node.js and Typescript project, but I'm facing an issue with generating proto files on Windows 10 using npm. I need to run the file transpile-proto-ts.sh: #!/usr/bin/env bash OUT_DIR="./src" TS_OUT_DIR="./src" ...

Tips for retrieving console data in VueJS Data

Is there a way to review data from a form component in the console without vue taking any action? I need to receive external data and fill in the fields accordingly. I attempted to set a value using document.getElementsByName("nfe.codigo")[0].value = "000 ...

Navigating a Collection of Elements in React/JSX

I am facing an issue while navigating through a collection of objects in JSX. renderBooks(book) { return( <div> A new book </div> {book.id}, {book.timeIn} ); } render() { console.log("the values are", this ...

Step-by-step guide on showcasing a quiz utilizing Magnific-popup and ajax

My goal is to create a functionality that allows users to easily download and view a quiz in a lightbox with just one click. I have successfully set up the ajax features and believe I am using Magnific-popup correctly, but for some reason, the lightbox is ...

How do you start the React number input control with an empty value?

My goal is to have the input field initially empty when controlled. Since it's a number input, passing an empty '' won't work. Instead, I use defaultProps to set the initial value of the input as null. However, upon typing into the inp ...

Testing of AngularJS Controller using Jasmine and Karma: "Error - Unable to read property 'then' of undefined"

I am currently attempting to perform unit testing on an AngularJS controller and encountering an error message while running Karma: Cannot read property 'then' of undefined I am unsure of what I am doing incorrectly. This is my first time con ...

Matrix mathematics with Python's numpy module

I am looking to efficiently multiply each row of two numpy arrays, a and b, to create a new array c with dimensions a-rows x b-rows. a = np.array[[1,2] [2,3] [3,4] [5,6]] b = np.array [[2,4] [6,8] ...

How can modifications be made to HTML strings passed through props in React?

I'm working on implementing a pre-loader icon before an image is rendered in a React component using the code snippet below: export default class MediaPostItem extends BaseComponent { public constructor(props: IMediaPostItemProperties) { ...

tips for retrieving global variables from ajax calls using promises

Currently, I am retrieving data and storing it in global variables in a less than optimal way. Here is the current method: var tranlationJson = $.ajax({ type: "GET", url: "translation.xml", contentType: "text/xml", dataType: "xml", ...

Step-by-step guide on saving an array to localStorage using AngularJS

Currently working on constructing a shopping cart. My goal is to include the array invoice in localstorage for future reference. I suspect there may be some flaws with this particular approach. angular.module('myApp', ['ngCookies']); ...