How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land).

Let's say we have a Set:

mySet = new Set([{item: SomeItem, selected: true}, ...])
.

Now, suppose we want to determine whether itemA: SomeItem is selected within the set.

What would be the most efficient way to accomplish this task?

The following attempts did not yield the desired result:

const isSelected = mySet.has({item: itemA, selected: true});

And neither did this:

const isSelected = Array.from(mySet).includes({item: itemA, selected: true});

This lack of success can be attributed to the fact that these approaches attempt to compare objects by reference rather than by value.

However, the following method does provide the expected outcome:

let isSelected: boolean;
mySet.forEach(state => {
  if (state.item === itemA) {
    isSelected = state.selected;
  }
});

Despite its effectiveness, I can't help but feel that there may be a more appropriate solution.

Therefore, How can I retrieve the value of a specific property from an object within a Set?

Answer №1

When comparing two objects with the same properties, it is important to note that they will only return true if they have the same reference. To accurately compare objects, it is recommended to compare their properties individually as these properties are primitive values.

To check if a specific object exists within a set, you can utilize the array some method for filtering.

let mySet = new Set([{item: 'SomeItem', selected: true}]);
let itemA = "SomeItem";
let isSelected =  Array.from(mySet).some(element => element.item === itemA);
console.log(isSelected);

Answer №2

Looking at it from a different perspective, Sets primarily return an iterable. Although they are hashed in order like a Map, based on your data structure, using a Map might be more advantageous in this scenario.

const x = new Set([
    { "foo": 1, selected: true },
    { "bar": 1, selected: false },
    { "baz": 1, selected: false },
    { "barf": 1, selected: false },
]);

To achieve your desired outcome, you'll need to convert the set into an array using Array.from (or use [...x] spread) and then iterate through to find the key.

Now, considering a Map:

const y = new Map();
y.set("foo", { selected: true });
y.set("bar", { selected: false });
y.set("baz", { selected: false });
y.set("barf", { selected: false });

With this approach, you just need to slightly adjust the structure to give item1 or any chosen Map key, and define the elements accordingly.

y.has("foo"); // true
y.get("foo").selected; //true

Therefore, if needed, you can easily obtain the iterable key name and determine which Map index contains the desired property.

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

Refresh KendoUI Grid data with latest additions

I currently possess: $.post('buying-grid/split/' + config.route.params.id, item).success(function(data){ var ds = new kendo.data.DataSource(); ds.data(data) $('#buyingGrid').data('ke ...

Guide to retrieving PDFs and images from a Spring Application as an API response and manipulating the data using JS/React

For my current project, I am working on a Spring Boot and React application where I need to create an API that takes the file name as input and returns the file content in Java/Spring Boot. The goal is to display the content in a new browser tab. Below is ...

Is it possible for TypeScript to automatically determine the specific type that was used in a union type parameter?

I need some help with a utility function I'm working on that can remove a specified number of elements from either a string or an array. My goal is to have the compiler determine whether the return value should be a string or an array based on what is ...

Is there a way to access an SD card by clicking on an HTML link using JavaScript?

UPDATE: I am seeking a way to embed an HTML file with JavaScript or jQuery that can directly access the contents of the SD card while being opened in a browser. Currently, I have posted code for accessing it through an activity, but I want to be able to d ...

CORS issue encountered by specific user visiting the hosted website

I recently developed a bot chatting website using Django and React, which I have hosted on HOSTINGER. The backend is being hosted using VPS. However, some users are able to see the full website while others encounter CORS errors where the APIs are not func ...

Tips for organizing an array of objects that contain null properties

Here is an array that I need help with: "data": { "risks": [ { "id": "22", "name": true, "surname": 0.5, "age": 0.75, "heigth" ...

React/NextJS: Firebase Realtime Database displaying the message "Error: Client is offline"

Encountering an occasional error when using React with NextJS to fetch data from a Firebase Realtime Database. Unhandled Runtime Error Error: Error: Client is offline. Currently utilizing Firebase version 9.0.1 for React. The initialisation and configura ...

Enhancing this testimonial slider with captivating animations

I have designed a testimonial slider with CSS3 and now I am looking to enhance it by adding some animation using Jquery. However, I am not sure how to integrate Jquery with this slider or which plugins would work best for this purpose. Can anyone provide g ...

Check a field for validation only when it is visible on the screen

One challenge I'm facing is with an asp.net webform. I have a hidden field that is only displayed when a user selects a radio button. The catch is, this hidden field needs to be mandatory only when it's visible; otherwise, I don't want it to ...

What is the best way to implement a series of delayed animations in jQuery that are connected

Imagine you have the following items: <div id="d1"><span>This is div1</span></div> <div id="d2"><span>This is div2</span></div> <div id="d3"><span>This is div3</sp ...

Using static assets within VueJS Components

I am currently working on a VueJS project that was customized from a base "webpack-simple" template provided by vue-cli, and it follows the folder structure below: My main focus right now is developing the "clickableimage.vue" component. However, I'm ...

Utilizing PUG for Iterating Through Multiple Items in Express Framework using JSON Data

I'm currently working on a small application using Express and PUG, aiming to achieve the following: https://i.stack.imgur.com/ZDyTK.png index.pug ul#restaurants-list li img.restaurant-img(alt='Mission Chinese Food', sr ...

Is it advisable to load 10,000 rows into memory within my Angular application?

Currently, I am in the process of creating a customer management tool using Angular.js that will allow me to directly load 10,000 customers into the $scope. This enables me to efficiently search for specific data and manipulate it without the need for serv ...

Issue with Node.js xml2js module: Sitemap attributes are not being recognized during creation

Currently, my project involves utilizing node.js and xml2js to generate an XML sitemap.xml. Everything seems to be in order, but when I try to define attributes like: '$': { 'xmlns': 'http://www.sitemaps.org/schemas/sitemap/0 ...

Switching a cookie from JavaScript to AngularJS: A step-by-step guide

Getting a cookie in AngularJS can be done in a more standardized way. Instead of the traditional JavaScript approach, you can implement it using AngularJS code as shown below: angular.module('myApp', []) .factory('CookieService', func ...

Discovering the smallest, largest, and average values across all properties in an array of objects

Given an array of objects with varying values, the task is to determine the minimum, maximum, and average of the properties in that array. For example, consider the following array: const array = [{ "a": "-0.06", "b": "0.25", "c": "-0.96", ...

Changing the time zone of a browser using JavaScript or jQuery

After researching numerous discussions on the topic, it appears that changing the browser's timezone programmatically is not possible. Although the moment-timezone.js library allows us to set timezone for its objects, it does not affect the browser&ap ...

What are the ways to enable VS Code's Intellisense to collaborate with AngularJS's injected services?

Hey, I've been trying to get Visual Studio Code to provide me with its intellisense for my unique framework (not Angular) app's services. Although I managed to get the standard type for such frameworks, I'm struggling to find a solution for ...

What are some ways to adjust red and green blocks using CSS?

One question that arises is how to create a version of a webpage where only the yellow block can slide up, while the red and green blocks remain fixed. Currently, the green block is treated with the following CSS: position:sticky; right:0px; top:100px; ...

Can you provide guidance on how to successfully transfer an array of JSON objects from the script section of an HTML file to the JavaScript

My webpage contains an array of JSON objects that I need to send to the server. The array, stored in a variable called results, appears normal when checked in the console before trying to POST it. Here is a sample of the data: 0: {id: 02934, uName: "Ben", ...