Determine using Lodash whether there is an object in an array that matches the ID from a separate array

There is a user array defined as follows:

var users = [{
 id: 1,
 name: 'ABC',
 isDisplay: true
}, {
 id: 2,
 name: 'XYZ',
 isDisplay: true
}, {
 id: 3,
 name: 'JKL',
 isDisplay: true
}];

Additionally, there is another array called selectedUsers which contains specific objects from the above array:

var selectedUsers = [{
 id: 1,
  name: 'ABC'
 },
 {
  id: 3,
  name: 'JKL'
}];

I want to determine which objects exist in the second array based on their ID, without using lodash.

 _.each(users, (_u) => {
     if(selectedUsers.includes(_u)) {
       _u.isDisplay = false;
     } else {
       _u.isDisplay = true;
     }
  });

My attempt to match entire objects using includes did not work because AngularJS automatically adds a $$hashkey property to objects. Is there an alternative method to achieve this?

Answer №1

let people = [{
 id: 1,
 name: 'Alice',
 isDisplayed: true
}, {
 id: 2,
 name: 'Bob',
 isDisplayed: true
}, {
 id: 3,
 name: 'Charlie',
 isDisplayed: true
}];

let chosenPeople = [{
 id: 1,
name: 'Alice'
},
{
id: 3,
name: 'Charlie'
}];

let commonSelection = _.intersectionBy(people, chosenPeople, 'id');

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

Answer №2

Follow these steps to create a Set of selected IDs called `selectedUsersIds`, iterate through the users array using Array#forEach, and update the value of the `isDisplay` property based on whether the user ID is included in the `selectedUsersIds` set:

const users = [{"id":1,"name":"ABC","isDisplay":true},{"id":2,"name":"XYZ","isDisplay":true},{"id":3,"name":"JKL","isDisplay":true}];

const selectedUsers = [{"id":1,"name":"ABC"},{"id":3,"name":"JKL"}];

const selectedUsersIds = new Set(selectedUsers.map(({ id }) => id));

users.forEach((user) => user.isDisplay = selectedUsersIds.has(user.id));

console.log(users);

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

Ways to collapse all rows that are expanded except the one that is currently open in iView Tables

Utilizing iView Tables to display data in a table with an expand option. As of now, when clicking on the expand button for a row, the row expands but previously expanded rows do not collapse, causing all expanded rows to be visible at once. Is there a wa ...

How can JavaScript be used to make an AJAX request to a server-side function?

I am diving into the world of AJAX and feeling a bit uncertain about how to structure my AJAX call. $.ajax({ type: "POST", url: "Default.aspx/function", data: '{ searchBy: id }', contentType: "application/json; charset=utf-8" }). ...

Having trouble loading the DOM element within the child component

An issue has arisen with Angular 4.4.6 regarding the access of a DOM element by ID from a different component. Within my component, I aim to display a Google Maps for specific purposes. Following the examples given in the API, I include the following code ...

Determine the quantity of items that meet specific criteria

The initial state of my store is set as follows: let initialState = { items: [], itemsCount: 0, completedCount: 0 }; Whenever I dispatch an action with the type ADD_ITEM, a new item gets added to the items array while also incrementing the count in ...

There appears to be an issue with reading the property 'toLowerCase' of an undefined element, and I'm having trouble identifying the error

The variables I have initialized (globally): var audio; var LANGUAGE; var audioArray; var MEDIAARRAY; var WORDS; var SOUNDARRAY; This specific line is causing the error: var audioId = MEDIAARRAY.audio.lowercase.indexOf(exObject['exerciseGetWordInpu ...

The MTM test runner is failing to identify AJAX callbacks

During my manual testing, I encountered an issue where the recorded test would get stuck after a button click and not proceed to the next page, causing the test to fail. This problem also occurred in CUIT, but I was able to resolve it using Ross McNab&apos ...

What sets Express.js apart from koa2.js in handling asynchronous functions?

I've encountered a situation where I had to set up the router using Express, and it was functioning correctly with the following code: router.get('/',(req,res)=>{ queries.getAll().then(stickers=>{ res.json(stickers) }) ...

Guide to dynamically inserting an audio file into a div with jQuery

I am looking to dynamically insert an audio file. Below are the declared tags: <div> <audio id="myaudio"> </audio> </div> Now, I am trying to add the source dynamically. Can anyone help me with how to add it to the div or audi ...

Is your Javascript navigation functioning properly on some submenus while encountering issues on others?

If you visit , you'll notice that it's a visually appealing site. The navigation submenus seem to be functioning properly, HOWEVER upon inspecting the element, you'll notice that under the PRICING tab, there are submenus that have the same c ...

Is it possible to utilize an npm package in TypeScript without a d.ts definition file?

Is it possible to use an npm package in TypeScript and Node.js without a .d.ts definition file? If so, how can I make it work? Currently, my code looks like this and I'm getting an error that says "cannot find module 'node-rest-client'" bec ...

Creating a Map in TypeScript from an Array

I have a series of TypeScript objects structured like this: interface MyObject { id: string, position: number } My goal is to transform this array into a map format where it shows the relationship between id and position, as needed for a future JSON ...

Error: The term "User" has not been previously defined

I encountered an issue while attempting to authenticate via vkontakte (vk.com) using passport-vkontakte. Error: A ReferenceError: User is not defined Below is the content of my auth.js file. var express = require('express'); var passport ...

Obtain information from the get request route in Node.js

I've been diving into nodejs and databases with the help of an online resource. As part of my learning process, I have been tasked with replicating the code below to fetch data from app.use('/server/profil'); However, I'm encountering ...

Enhance the progression bar using JavaScript

Is there a way to dynamically update a progress bar in HTML while a function is running? function fillProgressBar() { var totalIterations = 100; for (var i = 1; i <= totalIterations; i++) { //perform calculations progressBarWidth = (i/to ...

Pagination with React Material UI is a user-friendly and visually

Requirement Within the Material UI framework, I need to implement pagination functionality by clicking on the page numbers (e.g., 1, 2) to make an API call with a limit of 10 and an offset incrementing from 10 after the initial call. https://i.stack.imgur. ...

Create a dynamic image showcase using PHP or JavaScript

So I have a large collection of car photos organized in a structure similar to this (this is just a fictional example to illustrate my idea): Cars > Audi > Sports cars > '5 pictures' Cars > Audi > Family cars > '3 pictur ...

After changing the value of a <select> element in Vue, the fetched data is delayed by one step

I'm currently working on a feature that involves fetching data from a URL that changes every time a user chooses a new value from a <select> dropdown. The fetched data updates the songkickData array with the latest information. However, when I c ...

Can someone guide me on incorporating bluebird promises with request-extensible?

I'm interested in utilizing the bluebird library to create a promise-based asynchronous web client. Currently, I have been using the request-promise package for this purpose. To get started, I simply include the following lines of code at the beginnin ...

How can I update two divs simultaneously with just one ajax call?

Is there a way to update 2 divs using only one ajax request? The code for updating through ajax is in ajax-update.php. <?php include("config.inc.php"); include("user.inc.php"); $id = $_GET['id']; $item = New item($id); $result = $item->it ...

Executing various count() queries on a MongoDB using mongoose

Hey there, I consider myself a MongoNoob and I know this question has probably been asked before in various ways, but I haven't found a specific solution yet. Let's imagine I have two Moongoose Models set up like this: var pollSchema = mongoose. ...