JavaScript: Delete object with property equal to specified value

In my project, I am handling a JSON string that is stored in a Redis key. Whenever a user is added to another user's list, an object is added to this key. The dilemma I face is how to efficiently remove the object from the key where the 'name' property matches the value to be removed.

[{"name":"srtyt1","wins":0,"losses":0,"levels":0,"color":1672960,"avatar":[]},
 {"name":"srtyt2","wins":0,"losses":0,"levels":0,"color":1672960,"avatar":[]}, 
 {"name":"srtyt3","wins":0,"losses":0,"levels":0,"color":1672960,"avatar":[]} ]

After retrieving the result from Redis and parsing it into allFriends, I also set a variable called exFriend which stores one of the name properties.

Now, my main question arises: is there a way to eliminate the object with the name property matching "srtyt1"? Or will I need to rethink my data structure? While exploring solutions, I came across a loop in the Mozilla docs for maps, but unfortunately, it seems this approach does not work seamlessly with objects.

    let allFriends = JSON.parse(result);

    //iterate through all friends until I find the one to remove and then remove that index from the array
    for (let [index, friend] of allFriends) {
      if (friend.name === exFriend) {
        //remove the friend and leave
        allFriends.splice(index, 1);
        break;
      }
    }

Answer №1

If you're looking to extract specific items from an array based on the criteria that friend.name === exFriend, you can achieve this by applying a filter method like so:

const exFriend = 'srtyt1';
const inputArray = 
[{"name":"srtyt1","wins":0,"losses":0,"levels":0,"color":1672960,"avatar":[]},
 {"name":"srtyt2","wins":0,"losses":0,"levels":0,"color":1672960,"avatar":[]}, 
 {"name":"srtyt3","wins":0,"losses":0,"levels":0,"color":1672960,"avatar":[]} ];
 
 
 const outputArray = inputArray.filter(item => {
  
  return item.name !== exFriend;
 });
 
 console.log(outputArray);

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

Tips for eliminating default classes from Mui Typography styling

I’ve been working on creating a Typography element and noticed some default MUI CSS classes added when debugging in the browser. I attempted to disable them by using empty arrays at the end of the sx prop, but it did not work as expected. In the image p ...

Tips for retrieving the index of a selected option using Vue.js

Apologies for the beginner question. I am trying to figure out how to retrieve the index of a selected element from a select box and then execute a function. The following code snippet is not triggering the switchView() function as expected. <select id ...

$q: standard reject handler

I am looking for a way to ensure that when clients do not specify a reject handler in the 'then' function, a default one is automatically triggered. For example, let's say the default action is alert(1) In this scenario, calling mypromise. ...

Transformation of CSS classes in React with Webpack

Have you ever noticed that when you inspect the Airbnb website, the classnames appear to be morphed into single alphanumeric names? What is the name of this technique and is it applied at the code level or build level? https://i.sstatic.net/qSiaj.jpg ...

Utilizing JSON data with codeigniter

Hello there! I have a statement that echoes out my array of results using json_encode on my AJAX form. Now, I want to pass this array as $data to my Templatebuilder function as I plan to utilize the search as part of a larger template. I encountered an err ...

Unable to locate request object during post request

I've created a pug form with the following structure: extends layout block content h1 David A Hines h2 #{posts[0].title} p #{posts[0].body} div form(action='/insert_post',method='post') div(id='title_div' ...

Disabling the beforeunload confirmation popup

How can I prevent the appearance of this popup modal in Firefox and other browsers while working in React or vanillaJS? I attempted to remove the returnValue property of the event in my component using the snippet found here: https://developer.mozilla.org ...

Expanding the size of the number input in Twitter Bootstrap to accommodate changing content dimensions

I have a numeric input field that I want to customize in terms of width. I need the field to start with a minimum width so that -1, the default value, fits nicely inside. As the value changes, whether decreasing to -100 or increasing to -1,000 and beyond ...

Efficient method of delivering cohesive information from database to user without the need for continuous querying

Within the database, there is stored data about each user that typically remains constant. However, occasionally a user may update their information, such as changing their name. This data includes the user's name, username, and company details. The ...

Is there any issue that you can spot with this js / jQuery code?

Presented below is a script that prompts the user to confirm clicking a button based on a system setting. The system setting is saved in a hidden field established from the code-behind. Markup: <asp:HiddenField ID="hfConfirmOnApproval" runat="server" ...

Error occurs when attempting to create a PySpark dataframe in Databricks after upgrading from runtime 7.3LTS (Spark 3.0.1) to 9.1LTS (Spark 3.1.2) due to a duplicated column

Issue: When upgrading the Databricks runtime version, errors are encountered due to duplicate column(s) while creating a dataframe. In the previous runtime, the duplicates were ignored since they were not needed downstream. Data Source: Json files located ...

Creating a REST POST request that can accept JSON data: A step-by-step guide

I am currently delving into the world of RESTful web services and working on creating a simple set of web services. I hit a roadblock when I tackled the POST method. My goal is to pass JSON input to a POST method, and here is a snippet of the code where I ...

Having trouble downloading the Chip component in Material-UI? Learn how to fix the download issue

I used the UI to upload a file, and now I want to download it either after some time or instantly. I tried implementing this using the <Chip> component, but it's not working. I need assistance in resolving this issue. Uploaded File: const data ...

C# fails to accurately interpret JSON Arrays

I'm dealing with a peculiar JSON issue. I am currently using ASP C# and have a View that sends a JS-Array to a Controller Action. Here is the JSON Data structure: public class MapData { public List<Point> Points { get; set; } } public cla ...

Using VueJS to turn JSON data into a table for tallying unique values

Looking at the provided .json data: [{ "STATUS": "0500", "POSID": "..." }, { "STATUS": "1500", "POSID": "..." }, { "STATUS": "0500", "POSID": "..." }] I have a requirement to display this data in a table using vue-js with 2 columns. The first column shou ...

Tips on how to generate numerous JSON entities using a for loop

For my project, I am required to generate a variable number of JSON objects and arrays based on the data retrieved from a database query. The structure of the JSON is similar to the example below, which is commonly used for Google charts. { “cols”: [ ...

Utilize Lodash to group by ID and calculate the sum in order to assign the new sum value

Is it possible to use Lodash to sort and group by a specific key (such as "id") and update the values of the elements by adding all unique values of another key (e.g. payout)? For example, can we take the array below: [ { id: 1, payout: 15, ...

How can I ensure that the elements inside the '.box' are responsive, including dropdown buttons, text, and more?

I have successfully made my banner/header responsive, and I placed the dropdown buttons inside a box. I am new to bootstrap and pretty much new to everything, so I just copied some codes from demos. I need help making this specific box responsive along wit ...

Is the each() method in jQuery essentially a for loop?

Experimenting with adding a serialized class to a group of objects, I attempted the following approach: jQuery('#preload img').each(function(){ jQuery('#thumbs').append('<img class="index' + index + '" src="&apos ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...