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

Searching for a MongoDB document using its unique identifier

Currently, I am working with Node.js and MongoDB where my database is hosted on MongoHQ (now compose.io). I have come to understand that document IDs are converted to hex strings, but I am struggling to retrieve a document using its ID. In my dataset, the ...

Can a specific section of an array be mapped using Array.map()?

Currently, I am working on a project utilizing React.js as the front-end framework. There is a page where I am showcasing a complete data set to the user. The data set is stored in an Array consisting of JSON objects. To present this data to the user, I am ...

Exploring Validation Techniques in AngularJS

As I delve into AngularJS, my excitement grows. However, there seems to be a gap when it comes to validation. The current options, like the pre-installed mechanisms and the AngularUI project, use directives for validators, requiring each validation to be d ...

There seems to be an issue with ngOptions in Angular as it is

Calling all angularjs experts for assistance... Currently integrating cake with angular. Utilizing a rest controller to enable communication and retrieve options in a serialized json format as displayed below Attempting to populate dropdown options: &l ...

navigation through sibling views using query-based route in ui-router

Imagine an app with two sides: "left" and "right", each with tabs. The application's URL structure is formatted like this: app/splitscreen/?leftTab=1&rightTab=1 Currently, the HTML template is set up as follows: <!-- splitscreen.tpl.html --& ...

Struggling with getting Sprite maps to function properly within THREE.js

I'm having some trouble adding a sprite to my scene in the usual way. The image I'm using can be found here: i.imgur.com/kMT4mOH.png var map = THREE.ImageUtils.loadTexture('i.imgur.com/kMT4mOH.png'); var mat = new THREE.SpriteMaterial( ...

Pass information from ColdFusion to jQuery

I'm attempting to achieve a similar result as this, but I believe the syntax is not quite right: <cfset details = '{ name: "name", address:"address"}' /> <img data-details='#details#' onClick="DisplayDetails()" /> &l ...

Is it possible to verify the authenticity of published npm packages by utilizing hashes/checksums?

As I prepare to release an npm package on behalf of my organization, let's call it Organization A, I want our clients to have a means of verifying that the package they are using was indeed released by us. One method to accomplish this is by computing ...

Unsure of how to create a record of calculations made on the calculator

I am struggling with creating a calculator that includes a history feature. I have the basic functioning of the calculator working, but now I want to modify it so that it displays a history of operations performed by the user. The goal is for the history t ...

Exploring Javascript bugs in Visual Studio (or any other JS debugger)

I am currently working with a .js file that is executed using cscript.exe and not in a browser environment. I am aware that I can use the //X parameter with cscript.exe to trigger a debugger selection prompt. This works well when choosing "Visual Studio 2 ...

"Clicking on the hamburger menu causes the webpage to reset its scroll

I recently integrated a mobile hamburger menu into my website, which is primarily built around a single page. However, I noticed that whenever I open the menu, it automatically scrolls to the top of the page regardless of where you were previously scrollin ...

qunit timer reset

I have developed a user interface for manually launching qunit tests. However, I have noticed that the qunit test timer starts when displaying the interface, rather than when starting the actual test. For example: var myFunction = function (){ test ...

In order to successfully utilize Node.js, Async.js, and Listeners, one must ensure

Here is the log output from the code below, I am unsure why it is throwing an error. It seems that the numbers at the end of each line represent line number:char number. I will highlight some important line numbers within the code. Having trouble with t ...

Not defined within a function containing arrays from a separate file

Can anyone help me with listing multiple arrays from another file? When I try to iterate through each array using a "for" loop, the code compiles and lists everything but gives an undefined error at the end. How can I fix this? I have included some images ...

Unable to locate video identifier on ytdl

Lately, I have been working on developing a music bot for Discord. I have successfully managed to make it join and leave voice channels flawlessly, but playing music has proven to be quite challenging. For some reason, the play and playStream functions do ...

What is the best way to showcase response information on the website interface?

Recently, I have been utilizing GET requests to the github API: axios.get('https://api.github.com/users/roadtocode822') .then(function (response) { console.log(response.data); }) Successfully retrieving the response data. This particula ...

Unleashing the Power of Conditional HTML Attribute Insertion

What is the best way to add a conditional attribute in AngularJS? For instance, I am looking to only apply the multiple attribute to a <select> element if a certain binding in my component is set to true. If this binding is not present, then the mul ...

Work with JSON array objects

I am a novice in javascript and JSON. I have a requirement to process each JSON object, as shown in the example prototype below. Can someone please assist me in solving this problem? I need to log each room number given in the JSON sample below. How can I ...

Constructing a new mongoose request without nesting by sending multiple requests

Currently, I am working on an application where I receive a POST request with two variables. I then extract information from three collections based on these variables and use the collected data to make a save request to another collection. The structure o ...

Error: The method By.cssSelector is invalid and cannot be used

Currently utilizing npm's Selenium Webdriver. Having difficulty getting By.cssSelector to function properly. Other selectors like By.tagName and By.id are working fine. Here is the code snippet: var webdriver = require('selenium-webdriver&apos ...