What is the best way to utilize the .includes() method or comparable functions within an Object?

My task is to determine if the first argument includes the second one within an array of objects. Here is the example scenario:

whatIsInAName(
[
 { first: "Romeo", last: "Montague" },
 { first: "Mercutio", last: null }, 
 { first: "Tybalt", last: "Capulet" }
], 
{ last: "Capulet" });

I encountered a roadblock because I cannot utilize the includes() method since it's meant for arrays and not objects. Initially, I attempted to convert the objects in the whatIsInAName function into arrays using Object.entries(), but unfortunately, that approach did not yield the desired results. Now, I am contemplating two options - either transforming the objects into arrays or seeking an alternative method that can be applied to objects instead of the unavailable includes() method.

Are there any suggestions or insights you could offer on this matter?

Appreciate your help!

Answer №1

Utilize a some function to verify if the surname Capulet is present in an array:

let obj = { last: "Capulet" };
const isExist = whatIsInAName.some(f => f.last == obj.last)

const whatIsInAName = [
  { first: "Romeo", last: "Montague" },
  { first: "Mercutio", last: null },
  { first: "Tybalt", last: "Capulet" }
 ];

let obj = { last: "Capulet" };
const isExist = whatIsInAName.some(f => f.last == obj.last)
console.log(`Exists: ${isExist}`)

Alternatively, you can utilize the filter method to retrieve all objects based on specified criteria:

const whatIsInAName = [
  { first: "Romeo", last: "Montague" },
  { first: "Mercutio", last: null },
  { first: "Tybalt", last: "Capulet" }
 ];

let obj = { last: "Capulet" };
const result = whatIsInAName.filter(f => f.last == obj.last);

console.log(result)

Answer №2

One interesting approach is to create a custom includes function using some, which can outperform the traditional map/filter combination.

function myCustomIncludes(arr, obj) {
  return arr.some(({ lastName }) => lastName === obj.lastName);
}

const sampleArray = [{
    firstName: "Alice",
    lastName: "Smith"
  },
  {
    firstName: "Bob",
    lastName: null
  },
  {
    firstName: "Charlie",
    lastName: "Johnson"
  }
];

const testObject1 = {
  lastName: "Johnson"
};
const testObject2 = {
  lastName: "FOO"
};

const result1 = myCustomIncludes(sampleArray, testObject1);
const result2 = myCustomIncludes(sampleArray, testObject2);

console.log(result1);
console.log(result2);

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

Error in Redux app: Attempting to access the 'filter' property of an undefined value

I am currently encountering an issue with my reducer: https://i.stack.imgur.com/7xiHJ.jpg Regarding the props actual, this represents the time of airplane departure or arrival, and it is a property within my API. The API structure looks like this: {"body ...

How can I use the import statement to incorporate the 'posts.routes.js' file into my app using app?

Searching high and low for answers but coming up empty. When setting up an express app and including a file of routes, you typically encounter guidance on using the following statement: require('./app/routes/posts.routes.js')(app) As per nodejs. ...

Create a JSON object based on the data in the table

Can anyone assist me with generating a JSON file from a source that is imported (in my case, another JSON file)? Initially, I have successfully imported my JSON content: $Rules = get-content .\output.json | ConvertFrom-Json | select -expand Rules My ...

I am receiving all NFT IDs when I should only be getting the ones that are associated with the current account

I am facing an issue where I am receiving all NFTs token IDs instead of just the one that belongs to the current account. The code snippet causing this problem is as follows: const { enableWeb3, account, isWeb3Enabled, Moralis, deactivateWeb3 } = useMorali ...

What is the process by which Node can access predefined variables in clustering?

Consider the following code snippet: var running = false; var cluster = require('cluster'); if(cluster.isMaster){ cluster.fork(); running = true; } If this code is executed within multiple forks, would the value of 'running' ...

What steps are required to insert additional tags into select2?

I've successfully retrieved the tags from my API, but I'm facing an issue with adding new tags. Here's the code snippet I've been using: $(function(){ var user_email = localStorage.getItem('email'); var api = ...

Storing images from a URL in a database using Node.js

I recently started working with nodejs and I'm facing a challenge in saving an image obtained from a url (via api). Through my research, I found that using the createWriteStream method from nodejs could help me extract the image from the url and save ...

What are the steps to create a function that behaves like instanceof when given a string as input

Is there a way to achieve something similar to this? var isChild = isInstanceOf( var1, 'Constructor') so that it is equivalent to var isChild = (var1 instanceof Constructor) The challenge is that the function Constructor is not available in t ...

Invoking a directive function with a return value from a controller

I am working on a directive that contains a form with a simple input. I have multiple instances of this directive on the same page (index.html). Outside of these directives, there is a button that, when clicked, should gather data from all the inputs withi ...

What is causing this promise chain to not return in the correct order?

Struggling with creating a promise chain that returns results in the order they are called. The current output of resultArray has some data points swapped, causing issues for downstream processing. This is my current attempt: Promise.all(data.map( (dataPo ...

What is the reason behind tags being closed automatically?

When I use $("#ID").html("<p><div></div><span></p>");, the output appears as follows: <div id="ID"> <p><div></div><span></span></p> </div> The span tag is automatically closed ...

Error: Unable to use the map method on data in Reactjs because it is not

I'm currently working on a project with React.js and using Next.js as well. I'm attempting to fetch data from an API, but I keep encountering the following error: TypeError: data.map is not a function Below is the code snippet from the Slider.js ...

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

What causes the Vuetify checkbox to trigger twice when clicked in a Vue.js application?

I am facing an issue with a table that contains checkboxes in every row. I want to trigger some logic when a checkbox is clicked. In some cases, I need to tick multiple rows when a checkbox is clicked, so I have set the checkboxes as readonly and handle th ...

Instructions on selectively sorting an array within a MongoDB collection document

Seeking guidance as a newcomer to MongoDB. I am attempting to create a collection in my database with a single document that contains a key `cities`, which is an array comprising of 124247 objects. Below is the code snippet for reference: const express = ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

How to iterate through a JSON array using PHP

After browsing through numerous questions, I still can't seem to figure out how to make it work correctly. Here is the JSON: {"menu": { "title":"Title One", "link":"Link One", "title":"Title Two", "link":"Link Two"} } PHP Code: $st ...

Trouble encountered when utilizing jQuery for XML to HTML conversion and vice versa (CDATA mistakenly transformed into HTML comments)

I am in the process of developing a plugin/bookmarklet that is designed to extract an XML document from the <textarea> element on a web page, make modifications to the XML content, and then reinsert the updated version back into the <textarea> ...

Utilizing React with Firebase involves executing several Firebase requests simultaneously and ensuring the completion of all promises

I'm facing a challenge with the current code where it hits Firebase's 10 item limit in an array. My goal is to iterate through all teamIds and execute a Firebase query for each individual teamId. However, I'm unsure how to ensure that the ex ...

Using HTML and CSS to create interactive icons that change color when clicked, similar to how a link behaves

Have you ever wondered if there's a way to make an icon act like a link when clicked, just like regular text links turning purple? And not just the last one clicked, but every single icon that gets clicked. Trying to use the :visited pseudo was unsucc ...