One method of extracting an object from an array using a parameter function is by utilizing the following approach

I am searching for a specific object in an array based on the user-provided ID.

var laptops = [{
    "name": "Firefox",
    "age": 30,
    "id": "ab"
  },
  {
    "name": "Google",
    "age": 35,
    "id": "cd",
    "date": "00.02.1990"
  },
  {
    "name": "Microsoft",
    "id": "ef",
    "age": 40
  }
];

getLaptopByAsin(id: string) {
  var laptop = this.laptops.find(
    (laptopObject) => {
      return laptopObject.name === id;
    }
  );
  return laptop;
}
var enter = "cd";
name = this.getLaptopByAsin(enter).name;
age = this.getLaptopByAsin(enter).age;
date = this.getLaptopByAsin(enter).date;
console.log(name)
console.log(age)
console.log(date)

Answer №1

The issue you're facing is related to filtering by name:

this.laptops.find(
    (laptopObject) => {
      return laptopObject.name === id;
    }
 );

Once the problem is resolved and some restructuring is done, the code transforms into this:

getLaptopByAsin(id: string) {
  return this.laptops.find(
    laptopObject => laptopObject.id === id
  );
}

Additional comments to consider:

  • Opt for using const over var whenever possible.
  • The way you are storing dates may lead to complications in the future. It's beneficial to adopt a standard like https://en.wikipedia.org/wiki/Epoch instead.
  • Avoid unnecessary function calls. Store the result of getLaptopByAsin in a variable (const foundLaptop) to avoid iterating over the array multiple times. For example:

    const foundLaptop = this.getLaptopByAsin('cd'); console.log(foundLaptop.name); console.log(foundLaptop.age, foundLaptop.date);

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

How to convert form fields into JSON format using Angular 2

Currently, I am in the process of learning angular2 and have encountered a roadblock. I have created a form where the values are populated through JSON. The form consists of both pre-filled fields and text input fields where users can enter data and select ...

Check the @versionColumn value for validation prior to the entity save operation in TypeORM

I am currently in the process of saving data in a PostgreSQL database using TypeORM with NestJS integration. The data I am saving includes a version property, which is managed using TypeORM's @VersionColumn feature. This feature increments a number ea ...

Creating input fields using Vuejs

Currently, I am learning how to incorporate HTML content rendering in Vuejs. I'm experimenting with creating a small input component that is generated through the render function. Here is a snippet of what I have so far: export default { name: &qu ...

Pass information submitted through a JavaScript prompt to an expressjs endpoint

I'm currently facing a challenge in extracting the value from my prompt in order to modify a category using a JavaScript function. Typically, I would rely on a form to pass variables to the request.body, but that's not an option here. This is wh ...

What are some methods for altering ReadOnly values?

I am encountering an issue with the value fetchOptions: Readonly<HttpFetchOptionsWithPath> and my attempt to overwrite one of its properties. Here is the method I have tried: ((fetchOptions as Writable<HttpFetchOptionsWithPath>).headers as Wr ...

Enhance link with dynamic content using an AJAX call

I need help appending a picture after a link with the same URL as the link. The current AJAX code is producing the following result: <a href="images/Draadloos.png" data-lightbox="gallerij"></a> Here is an example of what I would like to achie ...

Switch button displaying stored data in sessionStorage

I am facing an issue with my small toggle button in AngularJS. I have set up sessionStorage to store a value (true or false), and upon page load, I retrieve this value from sessionStorage to display the toggle button accordingly. Depending on the value sto ...

Function that activates traffic lights

Currently, I'm encountering errors while working on this project in Notepad. Can you help me figure out what's wrong with my code? I'm attempting to create an onload traffic light using an object array. The requirement is to implement this f ...

The utilization of angular2-materialize is not possible due to an error message indicating that jQuery.easing is undefined

Greetings to all who are taking the time to read this. I am encountering an issue while trying to run ng serve. Here is the error message I am receiving: TypeError: jQuery.easing is undefined Here is a breakdown of what I have done so far: ng new X cd X ...

`The ng-binding directive seems to be malfunctioning while ng-model is functioning properly

Currently, I am in the process of learning how to utilize Angular (1.3.10). My objective is to create two input fields that will specify the suit and value for a hand of playing cards. In my attempts to achieve this, I have encountered an issue. When I man ...

Using Vue to dynamically wrap a component with a tag

Have you ever wondered how the v-if directive in Vue.js can hide an entire component along with its content based on a condition? I am curious to know: Is it possible to only hide the surrounding tag or component without removing its contents? ...

Why are NodeJS and Jade/Pug variables not being recognized in the Jade script?

After successfully passing a variable to Jade like #{myvar}, I encountered an issue when trying to access it in a script block. Despite using typeof(myvar) and confirming that it was initially undefined, my attempts to display its value within the script b ...

Using React with Typescript to display components generated from the `map` function

In my scenario, I have retrieved data from a JSON file and am also utilizing a utility function that selects 5 random entities from an object Array. This particular array contains 30 entities. Struggling with displaying the 5 random jockeys stored in the ...

Creating subclass mappings and defining subclasses dynamically using Typescript at runtime

I am puzzled by the structure of 3 classes: A, B, and C. Both B and C extend the abstract class A. abstract class A { public name: string; constructor(name: string) { this.name = name; } abstract getName(): string; } class B extends A { g ...

Working with jQuery, CSS, and functions to modify the current tag's class

Let's keep it brief and straightforward: Here is my HTML <div id="headerVideoControls" class="overlayElement"> <div id="videoMuteUnmute" onclick="muteUnmuteVideo('headerVideo')">mute button</div> </div> Edited ...

Is there a way to execute a node script via command line sans the need for installation and external packages?

Is there a way to execute a node script from the command line during development without actually installing anything, but still having access to installed packages using npm install <...>? When I try node ./bin/my_script.js, the script does not reco ...

Tips for transferring a DotNetObjectReference to a JS DOM event

My goal is to implement JS drag & drop in Blazor, which is working well overall. However, I am facing an issue where I want to set a custom drag image during the ondragstart event. Below is a snippet of my code: <div class="some-draggable-conta ...

Leveraging latitude and longitude data from an API to create circles on the AGM platform

I need assistance with utilizing location data from recent earthquake events to center a circle on Angular Google Maps. Can anyone provide guidance on how to achieve this? The API call provides the following data: 0: --geometry: ---coordinates: Array( ...

Error 404 encountered when updating packages in Angular2 tutorial: platform-browser-dynamic.umd.js

I recently started following an Angular2 tutorial, but upon returning to it and reaching the Routing chapter, I realized that the tutorial had been slightly updated. This required me to go back and update the package.json file to match the current version, ...

CSS Only Sidebar Dropdown (without using Bootstrap)

I want to create a sidebar with collapsible dropdown options and smooth animations using only pure css/js/html/jquery, without relying on bootstrap like I did in the past. Here is an example of what I created previously with bootstrap: Now, as a challenge ...