Utilize lodash to eliminate items from an array within an array

I am looking to eliminate users from the removeUser array based on their userName values using lodash. Here is the data I have:

{"users":[
{"title":"Mr", "firstName":"John", "lastName":"Doe", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e9838d868ca98e86868e858cc78a8684">[email protected]</a>", "userName" : "jdoe", "groups": [{"name": "Manager"}]},
{"title":"Ms", "firstName":"Anna", "lastName":"Smith","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c5d4f515548547c5b53535b5059125f5351">[email protected]</a>", "userName" : "asmith", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
{"title":"Mr", "firstName":"Peter", "lastName":"Jones", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d7d676263687e4d6a62626a6168236e6260">[email protected]</a>", "userName" : "pjones", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
{"title":"Ms", "firstName":"Jenny", "lastName":"Otter","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a3a6bdbdacbb89aea6a6aea5ace7aaa6a4">[email protected]</a>", "userName" : "jotter", "groups": [{"name": "Administrator"}, {"name": "Manager"}]}
]}

var removeUser = ['jdoe', 'asmith'];  //usernames of users to be removed

This is my current code snippet but it requires a foreach loop:

_remove(users, { userName: [removeUser]})

I would like to use the foreach loop to update the users array as follows:

{"users":[
{"title":"Mr", "firstName":"Peter", "lastName":"Jones", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2d2c8cdccc7d1e2c5cdcdc5cec78cc1cdcf">[email protected]</a>", "userName" : "pjones", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
{"title":"Ms", "firstName":"Jenny", "lastName":"Otter","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a10150e0e1f083a1d15151d161f54191517">[email protected]</a>", "userName" : "jotter", "groups": [{"name": "Administrator"}, {"name": "Manager"}]}
]}

Answer №1

When dealing with data manipulation, you have the option to utilize a callback function as the second argument. Here's an example:

var data = {"users": [
  {"title":"Mr", "firstName":"John", "lastName":"Doe", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c565853597c5b53535b5059125f5351">[email protected]</a>", "userName" : "jdoe", "groups": [{"name": "Manager"}]},
  {"title":"Ms", "firstName":"Anna", "lastName":"Smith","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8cedffe1e5f8e4ccebe3e3ebe0e9a2efe3e1">[email protected]</a>", "userName" : "asmith", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
  {"title":"Mr", "firstName":"Peter", "lastName":"Jones", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="adddc7c2c3c8deedcac2c2cac1c883cec2c0">[email protected]</a>", "userName" : "pjones", "groups": [{"name": "Administrator"}, {"name": "Manager"}]},
  {"title":"Ms", "firstName":"Jenny", "lastName":"Otter","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cba1a4bfbfaeb98baca4a4aca7aee5a8a4a6">[email protected]</a>", "userName" : "jotter", "groups": [{"name": "Administrator"}, {"name": "Manager"}]}
]};

var removeUser = ['jdoe', 'asmith']; 

_.remove(data.users, function(el) {
  // if el.userName exists in removeUser return true and remove it from data.users
  return removeUser.indexOf(el.userName) >= 0;
});

console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.9.0/lodash.js"></script>

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

Prevent repetitive content on your Node.js server

After realizing my small image hosting has many duplicate content, I am looking for a solution to prevent this issue in the future. My idea is to use either checksum or hash code so that whenever a new file is uploaded, it will be hashed and compared with ...

Jasmine attempting to access a nonexistent property

I created a very basic component: import { Component } from '@angular/core'; @Component({ selector: 'loading', templateUrl: './loading.component.html', styleUrls: ['./loading.component.scss'] }) export ...

switching the image source by selecting different options from a dropdown menu and leveraging JavaScript

I have been attempting to change the src of an image using JavaScript's addEventListener, but for some reason it is not working. Here is an example to illustrate my issue: let bulbImage = $.querySelector(".bulb-image"); let turnOnOption = $.querySele ...

What is the best way to generate dynamic components on the fly in ReactJS?

Could you please guide me on: Techniques to dynamically create react components, such as from simple objects? Is it possible to implement dynamic creation in JSX as well? Does react provide a method to retrieve a component after its creation, maybe b ...

Get rid of the spaces in web scraping <tr> tags using Node.js

I've encountered a problem that goes beyond my current knowledge. I'm attempting to web-scrape a specific webpage, targeting the <tr> element in nodejs. Although I can successfully retrieve the content, it seems that the format is not as cl ...

Issue occurring while trying to select an item from the dynamically generated options using AJAX

A JavaScript function is used in this code to select a specific option, with the option value being specified within a hidden element: $("select").each(function() { var id = $(this).attr('id'); var source = 'input:hidden[na ...

Combine object attributes to create a new column in a table

Check out this plunker I created. What is the most efficient way to merge the contents of $scope.blacklist into $scope.friends when ng-click="showColumn('Blacklist');" is triggered, and also add a new column named Coming to the table. Ng-App &am ...

How do I set up middleware with async/await in NestJS?

I am currently integrating bull-arena into my NestJS application. export class AppModule { configure(consumer: MiddlewareConsumer) { const queues = this.createArenaQueues(); const arena = Arena({ queues }, { disableListen: true }); consumer. ...

Updating the value of a rails parameter with JavaScript

I am trying to enhance my search form by pre-populating the fields with the "last searched values" when a user submits a search. The search form and results are displayed on the same page, and if there is no previous search, the fields should show placehol ...

What is the ideal MySQL data type for storing both plain text strings and encrypted hash values?

Tracking changes on my JPA Entities using an additional Entity/Table called Event: @Entity public class Event { private String fieldName; @Lob @Column private String previousValue; @Lob @Column private String newValue; // ... } The fi ...

What sets the Event and EventHandler apart from each other in terms of functionality?

I am posting this question to gain clarity on the fundamental distinctions and practical applications of the Event versus EvenHandler. ...

The dollar sign is not available during the onload event

Can someone help me with the error I am encountering where $ is unidentified when using onload on my page? This is a simple sample page created to call a function after the page has loaded. Jquery Code $(document).ready(function(){ alert("loaded"); }) ...

What methods can be used to center a Google map on a specific location?

I am facing an issue with three map canvases on different divs. Despite setting the center to the same position in all three of them using JavaScript, the second and third maps do not seem to reflect that center. Does anyone have any insights on what cou ...

Utilizing a jagged array with a limited number of indexes

I am currently working on an application that utilizes multiple "list of lists", but I find myself only accessing index 0 or 1 within these lists. Is this considered poor practice and could it potentially impact performance? To illustrate my situation, h ...

update/renew angularjs unique directive

Incorporating the carousel plugin from Ionic Market into my ionic project has been a game changer. This specific plugin, known as Morph Carousel, is a custom AngularJS directive that allows me to display content in a visually appealing way. One unique as ...

What is the correct way to insert an element into an array based on whether the elements already have values or not in PHP?

I have a task that involves the following code: $location1 = (isset($_POST['location1'])) ? $_POST['location1'] : null ; $location2 = (isset($_POST['location2'])) ? $_POST['location2'] : null ; $locations = array($l ...

Comparing NodeJS equivalents to window.location and window.pathname

Can anyone tell me how to achieve the same functionality as window.location.protocol and window.location.host in NodeJS/ExpressJS? I need to redirect the URL back to my website using a third-party API. Any advice is appreciated! ...

retrieve the variable contained within the callback function

const axios = require('axios'); const options = { url: 'https://api.github.com/repos/axios/axios', headers: { 'User-Agent': 'axios' } }; function handleResponse(error, response, body) { if (!error && re ...

Leveraging JSON for fetching distinct identifiers from a database

When a user hovers over a parent span containing an empty img tag, I use JSON and jQuery to retrieve the src of the image from the database. The issue arises when the retrieved src is applied to all looped span images on the same page, instead of each imag ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...