I am looking to create a unique object by searching for key-value pairs in an array containing 'n' number of objects, using either lodash or typescript

Here is my plan:

We have an array of objects retrieved from the database. Let's focus on one item: this.usersObj.

@Input() inlinetext: string; <<-- This represents the input field from the UI
public usersObj: string[]; <<-- Type definition for usersObj

[
    {
      "fname": "joe",
      "lname": "jones",
      "email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7ddd8d2f7ddd8d299d4d8da">[email protected]</a>"
    },{
      "fname": "pete",
      "lname": "daniels",
      "email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a6b3a2b396a6b3a2b3f8b5b9bb">[email protected]</a>"
    },{
      "fname": "peter",
      "lname": "stephens",
      "email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9c9dccddccbf9c9dccddccb97dad6d4">[email protected]</a>"
    },{
      "fname": "mary",
      "lname": "franklin",
      "email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cda0acbfb48da0acbfb4e3aea2a0">[email protected]</a>"
    },{
      "fname": "jane",
      "lname": "jefferson",
      "email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4329222d260329222d266d202c2e">[email protected]</a>"
    }
]

I'm currently using _.forOwn() to extract a specific group of people based on name search criteria such as first name, last name, or both.

In this instance, I am only searching by first name like so:

public getAllUsers(): Observable<Object> {

    let currUserObj: any;
    let allUsersObj: any;

    const endpoint = `${environment.SOCIAL_SHARE.users}/`;

    currUserObj = this._sessionUsersService.getSessionUsers(); // retrieve current users only
    allUsersObj = endpoint;


    console.log('currently logged session users ', currUserObj);
    console.log('all users endpoint: ', allUsersObj);

    this.http.get<Object>(`${endpoint}`, {headers: this.httpheaders}).subscribe(
      (response: any) => {
        this.usersObj = response;
        console.log('Get List of Reply Comments Response: ', this.usersObj);
        // Compare input value with DB entries
        this.getUsersOnly();
    }, (error: any) => {
       console.log('Get List of Reply Comments Error: ', error);
    }
  );

  return undefined;
}

public getUsersOnly(): Object {
    const self = this; // necessary evil for _.forOwn 
    let ctr = 0;

    _.forOwn(this.usersObj, function (value: any, key: any) {

    if (value.firstName !== undefined && value.lastName !== undefined) {
      if (value.firstName === self.inlinetext) {
        console.log('Found someone: ', key + ' : ' + value.firstName);
        self.retUsers.push(value); // PUSH method required here
      }
    }
  });
     ctr = 0;
     console.log('Found name object: ', this.retUsers);
     return this.retUsers;
}

If I enter "Pete", I expect to receive a list containing Pete and Peter within this.retUsers:

[
    {
      "fname": "pete",
      "lname": "daniels",
      "email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="403025342500302534256e232f2d">[email protected]</a>"
    },{
      "fname": "peter",
      "lname": "stephens",
      "email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c2d7c6d7c0f2c2d7c6d7c09cd1dddf">[email protected]</a>"
    }
]

If I type "Peter", only this result will be shown:

[
    {
      "fname": "peter",
      "lname": "stephens",
      "email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89f9ecfdecfbc9f9ecfdecfba7eae6e4">[email protected]</a>"
    }
]

The numeric values under "Pete" represent the keys of the corresponding values.

Any suggestions on how to improve this process?

UPDATE:

Solution involves using the PUSH method. self.retUsers.push(value); <-- THIS IS WHAT NEEDS TO BE DONE (PUSH)

BETTER UPDATE:

This method simplifies the process and eliminates the need for previous steps! Success!

_.forOwn(this.usersObj, function (value: any, key: any) {

  if (value.firstName !== undefined && value.lastName !== undefined) {
    if (value.firstName === self.inlinetext) {
      console.log('Found someone: ', key + ' : ' + value.firstName);
      self.retUsers.push(value); <-- THIS IS WHAT NEEDS TO BE DONE (PUSH)
    }
  }
});

Answer №1

your code is riddled with errors, and I suspect the main issue lies in the inconsistency between fname and firstName. Additionally, the structure of the code appears to be incorrect, making it difficult to pinpoint the exact problem.

Below is a basic example illustrating how to address this:

type UserItem = {
  fname?: string;
  lname?: string;
  email?: string;
}

class MyClass {
  public inlineText: string = ''
  public usersObj: UserItem[] = []

  public getUsersOnly(): UserItem[] {
    let txLower = this.inlineText.toLowerCase();

    return this.usersObj.filter(
      ({ fname }) => fname && fname.toLowerCase().startsWith(txLower)
    )
  }
}

const data = new MyClass();
data.usersObj = [
  {
    "fname": "joe",
    "lname": "jones",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117b7e74517b7e743f727e7c">[email protected]</a>"
  }, {
    "fname": "pete",
    "lname": "daniels",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="700015041530001504155e131f1d">[email protected]</a>"
  }, {
    "fname": "peter",
    "lname": "stephens",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="48382d3c2d3a08382d3c2d3a662b2725">[email protected]</a>"
  }, {
    "fname": "mary",
    "lname": "franklin",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0865697a714865697a71266b6765">[email protected]</a>"
  }, {
    "fname": "jane",
    "lname": "jefferson",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97fdf6f9f2d7fdf6f9f2b9f4f8fa">[email protected]</a>"
  }
]

data.inlineText = 'Pet'

console.log(data.getUsersOnly())

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

Encountering the error "Vue 2.0 encounters an undefined push during router.push

I'm currently working on a project that involves implementing a function to route the list of subMenus displayed by the mainMenu. Each subMenu is identified by its specific name, which I would like to append and use as the route path that I am aiming ...

Guide on showing a component exclusively for iPads with React and TypeScript

I need help displaying an icon only in the component for iPad devices, and not on other devices. As a beginner in coding for iPads and mobile devices, I am unsure how to achieve this specific requirement for the iPad device. Below is the code snippet tha ...

Executing JavaScript upon inserting it into the HTML of a webpage

On a webpage, I have content that is first sent from the server at page load and then frequently updated via AJAX. To handle this, I currently use $( function () {} ) for binding and updating based on the initial server data. However, I also need a way to ...

Labels can sometimes cause text input fields to become unresponsive

I've encountered a bug while working on my website with the materializecss framework. Sometimes, inputs are not responding correctly. This issue seems to occur when clicking on the first input and accidentally targeting the higher part of the second ...

I'm having trouble retrieving the object value from a different function within my Typescript and Express application

Currently I am experimenting with utilizing typescript alongside express for my application development. I have created a function that I intend to utilize in various sections of my codebase. Upon invoking the function, I am able to observe the values thro ...

Get a compressed folder from jszip containing a PDF file that is either empty or blank

I'm facing a challenge with my Vue app where I need to compress a group of PDF files in a folder using JSZip. While testing with just one file, the zip downloads successfully but when I try to open the PDF file inside it, the content appears blank. I ...

Distinguishing between an array of struct pointers and using malloc with struct pointers

working example: struct information{ int value; }; int main(void){ struct information *array[2]; (*array)->value = 6; printf("%d\n", (*array)->value); return 0; } segfault explanation: struct information{ int value; } ...

Could it be possible that my understanding of hoverIntent is incorrect?

I have a div that holds a series of li elements to construct a menu. Adjacent to the container ul, there is another div intended to appear only when an item in the original menu is hovered over. While I grasp the concept of mouseout and mouseover effects ...

Error: The file 'templates.js' cannot be found or accessed by gulp-angular-templatecache. Please check the file path and make sure it

I have set up a basic structure for creating angular templates using Gulp. Here is the code snippet from my gulpfile: var gulp = require("gulp"), templateCache = require('gulp-angular-templatecache'); gulp.task("tc", function() { retur ...

Incapable of merging various arrays together

I'm having difficulties merging the contents of arrays x and y to create array A. Unfortunately, I'm encountering multiple build errors in the process. The first error states "Consecutive declarations on a line must be separated by ';'" ...

What is the process for inserting additional information into a geoJson file?

In the "gj" object, I need to add new properties from the "dataToAdd" array. The current format of "gj" is as follows: const gj = { "type": "FeatureCollection", "features" : [ { "type": "Feature", "geometry": { ...

Discovering the Windows Identifier of the Opener Window in Chrome via JavaScript

I recently opened a link in a new window and realized that the current window's ID is now the ID of the newer window. I'm curious if there is any method to determine the window ID of the original window (the opener) from the perspective of the ne ...

Contrasting WebSQL and SQLite in terms of their utility in mobile applications and web browsers

Could you confirm if WebSQL and SQLite are the same? Are both WebSQL and SQLite available in PhoneGap? Will the JavaScript code used for WebSQL in a web browser be the same for a mobile app, or will we need different code? What advantages does WebSQL ha ...

Can the ES2016 Proxy be used to intercept the "typeof" operation?

Can a handler property be defined to intercept typeof proxyObject? It is not mentioned in any of the traps listed on Mozilla. ...

mat-autocomplete Show user-friendly names while storing corresponding IDs

I am currently utilizing a Mat-autocomplete feature that allows for loading a list of "users". Within the autocomplete functionality, I aim to exhibit the username while retaining the selected user ID value. Originally, I had: this.allFruits = val.map( ...

Is it possible to incorporate faces from an array into a THREE.BufferGeometry?

My task is to create a Mesh using a BufferGeometry. Right now, my geometry is handled by a worker. Worker: To begin with, I start by creating a Three.Geometry and then proceed to build my bufferGeometry before sending the data back to the main thread. 1. ...

The attribute 'inventory' cannot be found in the declaration of 'WarehouseModule'

I am facing an issue with my AngularFire setup. I have recently installed the latest version of AngularFire using npm i @angular/fire and have successfully configured Firestore. However, when attempting to load data into my Firestore database, I encounte ...

The React Bit Dev module is showing a 404 error

Attempting to incorporate the semantic-ui-react table reusable component from the Bit.dev community into my application. The link I am using is: To add this component to your application, use: npm i @bit/semantic-org.semantic-ui-react.table However, when ...

Attempting to convert Spotify's response string into a JSON object using Node.js

Lately, I've been utilizing the Spotify API through AJAX in the browser without any issues. However, now that I'm attempting to use it with node.js, I'm encountering a syntax error when trying to parse the string into a JSON object. Here&apo ...

Guide: Generating a DIV Element with DOM Instead of Using jQuery

Generate dynamic and user-defined positioning requires input parameters: offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth ...