Is there a way to determine if a certain property within an array of JavaScript objects exists in another array of objects?

Here are two arrays I'm working with:

const issues  = [{ id: 'foo', state: { label: 'bar'} }]
const states  = [{ label: 'bar' }, { label: 'baz' }]

I'm trying to filter the issue array to only include objects that have a matching state from the states array. Can someone help me with the correct approach?

This is what I tried, but it's not producing the desired result:

return issues.filter(issue => {
        return states.includes(issue.state)
 })

Answer №1

When it comes to comparing two objects with the same keys, it's important to remember that they are still distinct objects in memory. This means that using the equality or identity comparison operators between them will not yield the desired results. One way to address this issue effectively is by verifying that all the key/value pairs in each object are identical. To achieve this, I have implemented a custom function.

const issues  = [{ id: 'foo', state: { label: 'bar'} }]
const states  = [{ label: 'bar' }, { label: 'baz' }]

function objectsMatch(obj1, obj2) {
  const entries1 = Object.entries(obj1);
  const entries2 = Object.entries(obj2);
  if (entries1.length !== entries2.length) {
    return false;
  }
  return entries1.every(([key, value]) => {
    return obj2[key] === value;
  });
}

const matching = issues.filter(issue => {
  return states.some(state => objectsMatch(state, issue.state));
});

console.log(matching);

It's worth noting that while JSON.stringify could also be used for this task, it has limitations when dealing with complex objects such as functions, which cannot be accurately represented in JSON. This may lead to false positives in the comparison.

Answer №2

If all the data in your state can be converted to JSON format, like strings, booleans, numbers, null, and arrays/objects containing only data that can be converted to JSON, there is a quick method using a JSON set:

const items = [{ id: 'foo', data: { key: 'value'} }]
const dataList = [{ key: 'value' }, { key: 'anotherValue' }]

const dataSet = new Set(dataList.map(data => JSON.stringify(data)))

const filteredData = items.filter(item => dataSet.has(JSON.stringify(item.data)))

If you are unable to convert to JSON, you can instead use the deepCompare function from this answer, and apply it with some:

const items = [{ id: 'foo', data: { key: 'value'} }]
const dataList = [{ key: 'value' }, { key: 'anotherValue' }]

function deepCompare() {
    // ...
}

const filteredData = items.filter(item => dataList.some(data => deepCompare(data, item.data)))

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

The functionality of CDK Drag Drop is not accurately adjusting the placement of images

I have implemented an image gallery and am working on rearranging the position of the images using the Drag & Drop cdk library. However, I am facing an issue where the swapping of images does not always occur correctly; sometimes when attempting to exchan ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

Having trouble retrieving the value of an HTML input field using form.value in Angular 5?

I am currently working with Angular 5 Within my HTML, I am dynamically populating the value of an input field using: <input type="number" class="form-control" id="unitCost" name="unitCost" [(ngModel)]="unitCost" placeholder="Average Unit Price"> ...

Develop a new entity utilizing Array in Javascript

let DaysArray: any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] I am looking to transform the above array into an Object structure as shown below: let DaysObject: any = { time: { headerName: "" }, m ...

What is the significance of `(<typeof className>this.constructor)` in TypeScript?

After inspecting the source code of jQTree, written in Typescript, available at https://github.com/mbraak/jqTree, I came across the following snippet: export default class SimpleWidget{ protected static defaults = {}; ...

Is it possible to define an interface to inherit keys from another interface?

I have two different interfaces that I need to align their key structure, but not necessarily the values they hold. One interface (Thing) is sourced from an external library, while the other interface (ThingOptions) is defined in my own project. interface ...

What is the proper way to utilize a function in C# that integrates with a window form using TypeScript?

I am currently working on a code that is in c# and utilizes a web browser. My goal is to convert the existing JavaScript code to Angular 7 and Typescript. Below is the c# code and the corresponding JavaScript code used to access the c# function from JavaS ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

What is the definition of a type that has the potential to encompass any subtree within an object through recursive processes?

Consider the data structure below: const data = { animilia: { chordata: { mammalia: { carnivora: { canidae: { canis: 'lupus', vulpes: 'vulpe' } } } } }, ...

Unable to declare a string enum in TypeScript because string is not compatible

enum Animal { animal1 = 'animal1', animal2 = 'animal2', animal3 = 'animal3', animal4 = 'animal4', animal5 = 'animal5' } const species: Animal = 'animal' + num Why does typescr ...

I want to know the most effective way to showcase particular information on a separate page using Angular

Recently, I've been working with a mock json file that contains a list of products to be displayed on a Product page. My goal is to select a specific product, such as 'Product 1', and have only that product's information displayed on th ...

Dealing with TypeScript and the Mongoose loadClass problem

Working with Mongoose's class schemas has been very beneficial for me. Incorporating TypeScript into my Node project has enhanced the development process. I made sure to refer to Mongoose the Typescript way...? in order to ensure that my Model align ...

Avoiding redundant EventEmitters when transferring @Output to a child component

While working on a form component, I decided to separate the form action buttons into a child component. This led me to create two EventEmitter and handlers for the same action. I'm wondering if there is a way to directly pass the 'onDiscard&apo ...

Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service. This is the content of my component file: submitLoginForm() { if (this.loginForm.valid) { // send a http request to save t ...

Bringing in TypeScript definitions for gridster

After starting a new ionic project, I decided to include the gridster.js library by running npm install gridster and npm install @types/jquery.gridster in the root directory of my project. However, when trying to import the installed definitions, I encount ...

Inheriting Angular components: How can the life cycle hooks of a parent component be triggered?

So I'm working with BaseComponent and a number of child components that extend it: export class Child1Component extends BaseComponent implements OnInit, AfterViewInit In the case of Child1Component, there is no explicit call to super.ngAfterViewInit ...

Exploring the issue of nested subscriptions causing bugs in Angular

My current challenge involves nesting subscriptions within "subscribe" due to the dependency of some data on the response of the previous subscription. This data flows down the subscription chain until it is stored in an array. Starting with an array of I ...

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

What is causing the duplication of leaves when using this DFS implementation?

I created an algorithm to compare if two trees have the same leaves. https://i.sstatic.net/lpO2C.png Both trees display matching leaf numbers in the exact order, resulting in a true outcome. Below is the code that I formulated: function leafSimilar(root ...

Having trouble reading properties of undefined (specifically 'listen') during testing with Jest, Supertest, Express, Typescript

Issue: While running jest and supertest, I encounter an error before it even gets to the tests I have defined. The server works fine when using the start script, and the app is clearly defined. However, when running the test script, the app becomes undefi ...