Leveraging the find method to sort through an array with dual parameters

I'm facing an issue while trying to filter my array of objects using two parameters. Despite having an object in the array with the same values as the parameters, the result is empty.

const item = this.lista.find(i => i.number === rule.number &&  i.name === rule.name);

Even when attempting to use "filter", I encounter the same problem...

const item = this.lista.filter(i => i.number === rule.number).filter(i => 
 i.name === rule.name);

Below is my complete array:

  this.lista= [
            {number: 0, name: 'jose'},
            {number: 2, name: 'maria'},
            {number: 3, name: 'martha'},
            {number: 4, name: 'ana'},
            {number: 4, name: 'petter'},
        ];

And here is the rule object:

rule = new Rule();
rule.number = 4;
rule.name = 'ana';

Is there a more efficient way to achieve this?

Answer №1

It seems like there may be a small issue in your code, but I have created a simplified version based on your code and it is functioning correctly.

const condition = {};
condition.id = 3;
condition.name = 'john';

const array = [{
    id: 1,
    name: 'amy'
  },
  {
    id: 2,
    name: 'brian'
  },
  {
    id: 3,
    name: 'john'
  }
];

const result = array.find(item => item.id === condition.id && item.name === condition.name);

console.log(result);

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

Fix the TypeScript issue encountered during a CDK upgrade process

After upgrading to version 2.0 of CDK and running npm install, I encountered an issue with the code line Name: 'application-name'. const nonplclAppNames = configs['nonplclAppNames'].split(','); let nonplclAppNamesMatchingState ...

What is the rationale behind placing the CSS outside of the React function components, near the imports?

Recently, I encountered an issue with loading CSS inside a React function component using Material UI. Even though I managed to resolve it, I am still intrigued by the underlying reason. Initially, I had something like this setup where I placed both makeSt ...

Using POST in Android to send a byte array within JSON data

I am facing an issue with my JSON server (WCF REST) and a JSON POST method that requires an object containing id (string) and an image (byte[]): [DataContract(Name = "image")] public class CustomImage { [DataMember(Name = "id")] public string ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

Encountering difficulty in reaching the /login endpoint with TypeScript in Express framework

I'm currently working on a demo project using TypeScript and Express, but I've hit a roadblock that I can't seem to figure out. For this project, I've been following a tutorial series from this blog. However, after completing two parts ...

Having trouble with updating React state? The useEffect hook runs when attempting to change the state, but it seems to have the

Having worked with useEffect and its ability to trigger after a state variable has been updated, I am well-versed in its functionality. I'm currently drafting this post on my phone while away from home. Here's the setup I have: const [dateValue ...

Step-by-step guide on deploying Angular Universal

Exploring Angular universal and working on understanding deployment strategies. Check out the Github repository at https://github.com/angular/universal-starter This project includes Angular 2 Universal, TypeScript 2, and Webpack 2. After running the comm ...

There is no correlationId found within the realm of node.js

Currently, I am in the process of implementing correlationId functionality using express-correlation-id. I am diligently following the guidelines provided on this page: https://www.npmjs.com/package/express-correlation-id. I have successfully imported the ...

Verify the validity of an image URL

I am attempting to create a function in TypeScript that checks the validity of an image source URL. If the URL is valid, I want to display the image using React Native Image. If the URL is invalid, I would like to replace it with a local placeholder imag ...

working with JSON arrays in angular framework

Is there a way to print a specific value from an array in typescript? Below is the code snippet in typescript that I'm working with: import { AngularFirestore } from '@angular/fire/firestore'; export class ProfileComponent implements OnInit ...

Exploring distinct values in multidimensional arrays with varying key identifiers

Within my MySQL table, I store all website page loads with the following structure: [IP] [date] [hostname] The primary query used is: $log = mysqli_query($con, "SELECT * FROM log"); Subsequently, all values are stored in an array: while ($result = my ...

A guide on iterating through a JSON object fetched using Http in Angular 2/Typescript

I am attempting to extract specific data from my JSON file using http. The structure of the JSON is as follows: [{"name":"Name1","perc":33},{"name":"Name2","perc":22},{"name":"Name3","perc":41}] To loop through this retrieved object, I use the following ...

Ensuring strictNullChecks in Typescript is crucial when passing values between functions

When using the --strictNullChecks flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is ...

"What is the significance of the .default property in scss modules when used with typescript

When dealing with scss modules in a TypeScript environment, my modules are saved within a property named default. Button-styles.scss .button { background-color: black; } index.tsx import * as React from 'react'; import * as styles from ' ...

Set the default requests header in Ionic 3 using data stored in Ionic Storage

This particular issue is related to retrieving a value from local storage. I am trying to set the default header (Authorization token) for all requests, but I can't seem to find a solution that works efficiently. Most of the resources available only e ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

Is it necessary for me to set up @types/node? It appears that VSCode comes with it pre-installed

Many individuals have been adding @types/node to their development dependencies. Yet, if you were to open a blank folder in VSCode and create an empty JavaScript file, then input: const fs = require('fs'); // <= hover it and the type display ...

What is the correct way to construct an object in TypeScript while still taking types into account?

Hey, I'm having trouble implementing a common JavaScript pattern in TypeScript without resorting to using any to ignore the types. My goal is to write a function that constructs an object based on certain conditions and returns the correct type. Here& ...

I'm experiencing difficulties in establishing a connection from Ionic to my remote database

I set up a database on Fauxten and now I'm trying to connect it to my project. Although I can open the link in my browser, nothing happens when I try to call it in the app. I can't figure out what I'm missing. import { Injectable } from &ap ...

Looking to query JSON using jQuery - how can I accomplish this?

Currently, I am utilizing session storage to temporarily store data and attempting to search for a specific string (CatalogNumber) within the session data. If the string is not found, my goal is to add it. Despite my efforts, I have encountered issues wit ...