Is there a way to verify the presence of a complete object by using a specific key in JavaScript

As I loop through my data, I only want to assign a random number to a fontObj if it is unique.

A typical fontObj consists of:

{
   postscript: "Calibri",
   style: "Bold",
   family: "Calibri"
}

In my code, I aim to iterate through paragraphs and utilize the fontObj as a key.

Here's some pseudocode to illustrate my approach:

if (fontMap[fontObj]) {
   console.log("Already found: " + fontObj + " and the random number is " + fontMap[fontObj])
} else {
   fontMap[fontObj] = Math.random()
}

I'm exploring the best way to structure this since I cannot directly check for the existence of an entire object using just a key. Any insights?

Answer №1

An object cannot serve as a key; you must utilize a string instead.

If the objects share identical properties, convert those values into a string.

function transformObjToKey(obj) {
    return `${obj.property1}/${obj.property2}/${obj.property3}`;
}

let uniqueKey = transformObjToKey(obj);
if (keyMap[uniqueKey]) {
    console.log("Found duplicate: " + uniqueKey + " and the generated number is " + keyMap[uniqueKey]);
} else {
    keyMap[uniqueKey] = Math.random();
}

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

Can one intercept the window.location.replace event?

Suppose I am currently browsing the URL "example.com/somepage#somehash" and then decide to execute window.location.hash = "anotherhash", the URL will be updated to "example.com/somepage#anotherhash". This action triggers the window.hashashchange event. On ...

The presence of the !doctype html tag completely messes up my

I am currently working on a code snippet that is supposed to provide the screen coordinates of a given object: <!DOCTYPE HTML> <html> <head> </head> <body style="margin:0px;padding:0px;"> <div id="help" style="top:100px;r ...

Looking for a way to utilize JavaScript to extract data from a database? I'm currently utilizing jQuery autocomplete and seeking to exclusively search for values within the database

Currently utilizing jQuery autocomplete <script> $(function() { var availableTags = [ "ActionScript", "AppleScript", "Scheme" ]; $( "#tags" ).autocomplete({ source: availableTags });}); </script> Any s ...

Is there a way to prevent the entire row from being selected when a radio button is clicked in an md-data

Can anyone assist me with an issue I am having with my data table? When I select a radio button, the entire table row is getting selected instead of just the radio button. Below is the code snippet: https://i.sstatic.net/dicwF.png My Expectation: When c ...

A guide to retrieve data attributes in Vue.js

When my button is clicked, a modal pops up with data passed through data attributes. The button code looks like this: <button class="edit-modal btn btn-info" data-toggle="modal" data-target="#editModal" :data-id=item.id ...

The command "actions" in Selenium is not recognized

I am having trouble trying to perform a mouse click based on position. No matter what I try, I keep receiving the same error message. I encountered this issue when attempting a double click on the main search bar of google.com. For assistance, refer to: ...

Concealing HTML pages in Node.js: A step-by-step guide

I have a specific requirement where my website's html pages should only be accessible to users who are logged in. However, when I used the command below, my html pages became public: app.use(express.static('public')); For instance, I do no ...

Bootstrap UI Tab presents an obstacle for Google Map functionality

When utilizing the Bootstrap Tabset to include a Bootstrap slider, Google Map, and other pages, I encountered an issue where the slider functions perfectly but the Google Map does not work as expected. Interestingly, the map works perfectly in street view ...

The use of DIV tags allows the element to be displayed in an inline

In my project, I decided to add three div tags. The first two are positioned next to each other with the third div tag placed below them. However, when I tried to insert a slideshow into the first div tag, all of the div tags ended up displaying as "block" ...

Example TypeScript code: Use the following function in Angular 5 to calculate the total by summing up the subtotals. This function multiplies the price by the quantity

I have a table shown in the image. I am looking to create a function that calculates price* quantity = subtotal for each row, and then sum up all the subtotals to get the total amount with Total=Sum(Subtotal). https://i.stack.imgur.com/4JjfL.png This is ...

Exploring the wonders of Onsen UI's ng-repeat feature combined

Facing a major issue with my app, and I suspect it's due to the asynchronous call. The HTML section looks like this: <ons-list ng-repeat="item in newsEventi.items"> <ons-list-header class="news_titolo_lista">{{item.categoria}}</ons ...

Utilize the search bar within a JavaScript function

One issue I am facing is taking an input from a search box and using that value as a parameter for another function. However, every time I click the button, the global variable resets itself when the page refreshes. In my javascript code, this is what I h ...

Could the act of one function updating state and another immediately accessing it lead to a potential race condition occurring?

I am faced with a scenario where I have two components - one for uploading files and the other for submitting a form. Each component has its own callback function that needs to trigger a backend request once completed. My objective is to ensure that the ba ...

Extracting information from ul li div elements and saving it in JSON format

I have been pondering this issue for the past few hours and haven't been able to find a solution. Essentially, I have a list structured like this <ul class="list"> <li class="user"> <div class="name">Name</div> ...

Tips for displaying only one image when clicked and hiding other divs:

Currently tackling a project that involves JavaScript and I've hit a roadblock. Before you dive into the text, take a look at the image. Check out the picture here. I have successfully created a slider, but now I want to implement a feature where cli ...

When utilizing a prisma query with a callback function, it appears that try/catch blocks are being overlooked in Node.js

After referencing error handling methods from the prisma documentation, I encountered an issue with my code: try { prisma.daRevisionare.create({ data: { "idTweet": tweet.id, "testo": testotweet, url } }).then((dati) => { bo ...

Are the buttons appearing within a pop-up display?

I am having an issue with my Javascript popup buttons. Whenever the popup appears, the buttons that come after the one clicked appear on top of the popup container, and the previous buttons appear behind it. How can I ensure that the popup container displa ...

What is the best way to create a keyup event for the entire document except for one specific element?

Looking for some advice on how to handle a specific code scenario. Here's what I have: $(document).ready(function(){ $(document).on("keyup",function(e){myFunction(e)}); }); function myFunction(e){ console.log("hi"); } In ...

The sequence of elements within a React.addons.createFragment object

Currently, I am exploring the documentation on creating fragments in React from https://facebook.github.io/react/docs/create-fragment.html. It appears that the engineers at Facebook place a significant emphasis on the object memory layout, specifically the ...

Issue with undefined arrays in the Angular merge sort visualization tool

I am currently working on developing a visualizer for sorting algorithms using Angular. However, I have encountered some difficulties while implementing merge sort. As a Java programmer, I suspect that there may be an issue with my TypeScript code and the ...