Discover and allocate personalized entity

My goal is to locate an item in a list and transfer some of its attributes to another item. The code I currently have feels messy and inefficient.

this.myResult = {value1: null, value2: null};
this.myArray = [
  { a: 'test1', b: 1, c: {subObject1}},
  { a: 'test2', b: 2, c: {subObject2}}
];

let result = this.myArray.find(myObject => myObject.b === 2);

this.myResult = {
   value1: result.a,
   value2: result.b
}

Is there a more elegant way to utilize the result of the Array.find() function in another lambda function and update myResult without the need for a temporary variable? I'm exploring options similar to the following code snippet, and willing to consider the use of libraries like lodash.

this.myResult = {value1: null, value2: null};
this.myArray = [
  { a: 'test1', b: 1, c: {subObject1}},
  { a: 'test2', b: 2, c: {subObject2}}

this.myArray
  .find(myObject => myObject.b === 2)
  .then(result => {
    this.myResult = {
      value1: result.a,
      value2: result.b
    }
  });

EDIT:

After discussions in the comments, I am interested in a solution involving something akin to a .map function following the .find

this.myResult = {value1: null, value2: null};
this.myArray = [
  { a: 'test1', b: 1, c: {subObject1}},
  { a: 'test2', b: 2, c: {subObject2}}

this.myArray
  .find(myObject => myObject.b === 2)
  .map(result => {
    this.myResult = {
      value1: result.a,
      value2: result.b
    }
  });

Answer №1

Let's delve into the concept you explored in your second code snippet, where you discussed the solution you desire using the .then() method.

The concept of function chaining involves performing sequential operations on a value, especially when working with iterable objects like arrays.

For instance:

[1, 2, 3].map(fn1).toSorted(fn2).with(fn3)

In this scenario, each function within the chain accepts a callback that gets executed for each element in the array. However, the challenge arises when you simply want to pass the result of the previous operation to another function within the same chain.

Similar to your situation:

// Note: `.doOperation()` is akin to your `.then()`. 
// I opt for the former to prevent confusion with promises.
arr.find(fn1).doOperation((val) => ...)

Regrettably, achieving this directly in JavaScript is not feasible. In other programming languages, this concept is known as piping, with a dedicated operator for it to link expressions together seamlessly.

There is currently a proposal at stage 2 for introducing a piping operator: https://github.com/tc39/proposal-pipeline-operator

If this proposal gets approved in the future, you may be able to implement something like this:

let result = arr.find(fn1) |> (foundValue) => {
  return {
    a: foundValue.a,
    b: foundValue.b
  }
}

You may explore using methods like .reduce() or .forEach() to achieve this without the need for a temporary variable, although it might not align exactly with your desired outcome. Alternatively, to eliminate the temporary variable, you can utilize an IIFE as shown below:

let arr = [
  { a: 'test1', b: 1, c: {subObject1}},
  { a: 'test2', b: 2, c: {subObject2}},
  { a: 'test3', b: 3, c: {subObject3}},
];

let res = (({ a, b }) => ({ a, b }))(arr.find(obj => obj.b === 2))

Answer №2

Do you think this approach would suit your needs? Assuming that there will only be 1 or 0 matching elements in your array.

It involves filtering the array to create a list of matching elements (in this case, either 1 or 0 elements). Then, we will reduce the array to a single value. If filter() results in an empty array, reduce() will return a default value.

this.myArray = [
  { a: 'test1', b: 1, c: {subObject1},
  { a: 'test2', b: 2, c: {subObject2}
];

this.myResult = this.myArray
    .filter(myObject => myObject.b === 2)
    .reduce((res, curr) => {
        return {
            value1: curr.a,
            value2: curr.b
        }
    }, {value1: null, value2: null});

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

Implementing Class-based Dependency Injection in Express

Incorporating Express into a TypeScript project has presented me with a particular scenario Here is my route file: ... import findAllUsersFactory from "src/factory/FindAllUsers"; routes.get("/users", findAllUsersFactory().handle); ... ...

Prisma allows for establishing one-to-many relationships with itself, enabling complex data connections

I am in the process of developing a simple app similar to Tinder using Prisma. In this app, users can swipe left or right to like or dislike other users. I want to be able to retrieve matches (users who also like me) and candidates (all users except myself ...

Hide the FormArray in a Reactive Form if it is not populated or cannot be determined

As a newcomer to Angular 4, I've embarked on my first project and started learning the ropes. I have devised a Reactive Form to showcase a form structure that looks like this: Form (FormGroup) | --> aggLevels (FormArray) | --> ...

What is the best way to specify data types for all attributes within an interface?

In building an interface for delivering strings in an i18n application: interface ILocaleStringsProvider { 'foo': string 'bar': string 'baz': string 'blablabla': string // numerous other string properties ...

Encountered issue with accessing the Error Object in the Error Handling Middleware

Below is the custom error validation code that I have developed : .custom(async (username) => { const user = await UserModel.findOne({ username }) if (user) throw new ConflictError('username already used& ...

Updating nested forms in Angular 4

The nested form structure I am working with is a 'triple level' setup: FormGroup->ArrayOfFormGroups->FormGroup At the top level (myForm): this.fb.group({ name: '', description: '', q ...

Tips for adjusting the timing of an interval in Angular and RxJS to create dynamic changes

I am looking to dynamically adjust the delay of an interval, but my knowledge of Angular is limited which is hindering my progress in this task. Below is the current code snippet I am working with: timeDiffs : number[] = [] <== this array contains time ...

The attribute 'prop' is not found on the type 'IntrinsicAttributes & TableProp'.ts(2322)

Encountering an error while trying to pass a prop to a React component for the first time. Despite looking at other posts for solutions, I have been unable to resolve it so far. Here is a snippet of my code: type TableProp = {}; function Table(prop: Tabl ...

The 'this' context setting function is not functioning as expected

Within my Vue component, I am currently working with the following code: import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, value: any, callback: ...

What methods are available to extract HTML elements from .ts files?

Exploring Angular development has been quite a challenge for me. I've heard that typescript is an extension of javascript, but when it comes to manipulating HTML elements in the .ts file, I seem to be at a loss. I attempted a simple document.getEleme ...

Alert: User is currently engaging in typing activity, utilizing a streamlined RXJS approach

In my current project, I am in the process of adding a feature that shows when a user is typing in a multi-user chat room. Despite my limited understanding of RXJS, I managed to come up with the code snippet below which satisfies the basic requirements for ...

Using dynamic parameters in React Router v4

Looking to implement dynamic routing in my React app using React-Router v4. I am aiming to construct the following address: http://localhost:7777/oceanside-yaht-club/booking/search where oceanside-yaht-club can change based on the customer. However, my ...

Is the input URL modified by the Angular HttpClientModule's GET request?

I am currently using an Angular service to make calls to a Node.js server in order to fetch data. Here is a snippet of my code: constructor(private http: HttpClient){ } getPersonData(): Observable<person[]> { //return this.http.get<person ...

Exploring Mikro-ORM with Ben Awad's Lireddit: Navigating the Process of Running Initial Migrations

Having some trouble following the lireddit tutorial, particularly with the initial mikro-orm migration step. Encountering a similar issue as mentioned in this post. Tried modifying the constructor of the example entity (tried both provided format and the ...

Combine a pair of select statements to utilize the RxJS store within an Angular Guard

When working on an Angular Guard, I encountered a challenge where I needed to select two fields from the ngrx store. Here is the code snippet for reference: @Injectable() export class RoleGuard implements CanActivate { constructor( public router: A ...

What is the best way to handle typing arguments with different object types in TypeScript?

Currently, I have a function that generates input fields dynamically based on data received from the backend. To ensure proper typing, I've defined interfaces for each type of input field: interface TPField { // CRM id as a hash. id: string nam ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

Having trouble with implementing custom checkboxes in a d3 legend?

My attempt at creating checkboxes in d3 has hit a snag. Upon mouse click, the intention is for them to be filled with an "x". Strangely, using d3.select() inside the click-function doesn't seem to work as expected, although adding the letter U for the ...

Retrieving the final element from a TypeScript JSON array

I am trying to retrieve the value of the "id" property from the last element in an array of JSON objects. While I can easily find each element by id, I specifically need to extract the value of the last "id" in the array of JSON objects. In the example p ...

Showing json information in input area using Angular 10

I'm facing an issue with editing a form after pulling data from an API. The values I retrieve are all null, leading to undefined errors. What could be the problem here? Here's what I've tried so far: async ngOnInit(): Promise<void> ...