ways to insert a fresh value into a recently instantiated object in typescript

I am currently using Angular 6 and dealing with arrays. I have an array along with a model.

Here is the Array:

let array = [
    {
        id: 1,
        value: "Some Value",
        description: "Some Description"
    },
    {
        id: 2,
        value: "Some Value",
        description: "Some Description"
    },
    {
        id: 3,
        value: "Some Value",
        description: "Some Description"
    },
]

Now, let's take a look at the Model:

export class Data{
    index: number;
    id: number;
    value: string;
    description: string;

    constructor(data){
        this.index = null;
        this.id = data.id;
        this.value = data.value;
        this.description = data.description;
    }
}

When selecting an item from the array, a new object is created using this method.

selectItem(index, data){
    let selectedItem = new Data(data);
    console.log(selectedItem);
}

The expected result is:

{
    id: 1,
    value: "Some Value",
    description: "Some Description"
}

In this scenario, it becomes challenging to include the index value in the newly created object as the data object lacks this parameter.

To address this issue, I implement the following approach:

selectItem(index, data){
   let selectedItem = new Data({
       index : index,
       id : data.id,
       value : data.value,
       description : data.description
   })
}

Now onto my query: Is there a way to add additional parameters while creating a new object utilizing models? A similar concept is illustrated below:

selectItem(index, data){
    let selectedItem = new Data({data}).index = index
}

Answer №1

In order to provide more flexibility in your constructor, consider adding an optional parameter.

export class Data{
  index: number | null;
  id: number;
  value: string;
  description: string;

  constructor(data, index: number | null = null){
    this.index = index;
    this.id = data.id;
    this.value = data.value;
    this.description = data.description;
  }
}

This way, you can create instances of the Data class with or without specifying an index

selectItem(index, data){
  let selectedItem = new Data(data, index);
}

If needed, you can still create objects without providing an index

let selectedItem = new Data(data);

Answer №2

It is not possible to create a new object Data within the Data class. You can attempt the following method:

export interface Information {
     position: number;
     identity:number;
     content:string;
     details:string
}

chooseData(position, information):Information{
    let outcome:Information = {
       position: position,
       identity: this.identity, 
       content: this.content, 
       details: this.details
    };
    return outcome;
}

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

Exploring ways to locate a specific text within a URL using nodeJS

Here is a simple code snippet with a problem to solve: var S = require('string'); function checkBlacklist(inputString) { var blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"]; var found = false; for (var i = 0; i < b ...

Is there a Node template engine similar to EJS that seamlessly integrates with HTML templates?

Is there a template engine for NodeJS similar to EJS that doesn't alter the original HTML template structure with its use of parentheses? In EJS, one might utilize the following code snippet to embed specific data into the HTML template: <script& ...

Utilize a standard PHP script for every subdirectory within a domain

I'm currently working on a website and the design I'm using involves changing the URL in the address bar using the history API when the page content changes through JavaScript and AJAX. However, I also want each "page" of the website to be access ...

Tips for ensuring a custom menu closes when clicking outside of it instead of on the menu itself

Building off a recent inquiry, I am aiming to have my menu close whenever I click outside of it. At the moment, clicking the "Hamburger Menu Button" opens and closes the menu. It will also close when I click a link on the menu or the menu itself. However, ...

Demonstration of using .queue() and .dequeue() in relation to $.queue() and $.dequeue()

I successfully completed an animation using animate(), queue(), and dequeue(). However, I recently discovered that jQuery also offers jquery.queue() or $.queue() and jquery.dequeue() or $.dequeue(). Can anyone assist me in understanding these new terms w ...

Issue in Ionic 2: typescript: The identifier 'EventStaffLogService' could not be located

I encountered an error after updating the app scripts. Although I've installed the latest version, I am not familiar with typescript. The code used to function properly before I executed the update. cli $ ionic serve Running 'serve:before' ...

Convert inline javascript into an external function and update the reference to `this`

I'm currently in the process of converting some inline JavaScript code triggered by a button's onclick event to a regular JavaScript function. In my previous implementation, I successfully used the "this" reference to remove a table column. Howe ...

Avoid blurriness caused by entering data in v-combobox

When using <v-combobox> in Vuetify.js, I noticed that when I click away, the value I had typed gets added to the model automatically. Is there a way to prevent this behavior? Check out the official documentation for Vuetify combobox here View the ...

Can builtins like DOM globals be explicitly imported?

The present situation includes the utilization of rollup (as well as iife parameters), but I am hesitant about whether it is solely related to rollup or typescript. My objective is to achieve something similar to this: import { document } from "[wherever ...

Execute AJAX function following the completion of table loading from PHP in Ajax

I'm currently working on a shopping cart feature that involves calculating certain figures based on table values. The process involves loading the table using AJAX and PHP, which is functioning properly. However, I'm facing an issue where I nee ...

Guide on making a color legend with JavaScript hover effects

On my website, there is a dynamic element that displays a table when values are present and hides it when there are no values. The values in the table are color-coded to represent different definitions. I wanted to add hover text with a color key for these ...

Creating visually appealing transition effects like sliding in an autocomplete feature can enhance the user experience and

I have successfully implemented autocomplete functionality, but now I am looking to add a transition effect (slide down) to the suggested menu. After researching online, I found a helpful tutorial on this topic: Based on the information I gathered, I tri ...

What is the rationale behind permitting surplus properties in Typescript interfaces even though all properties are declared as optional?

Exploring the code snippet... interface Options { allowed?: string; } function test(options: Options) { return options; } const options = { allowed: 'allowed', notAllowed: 'notAllowed', }; test(options); // no error thrown ...

The parent component's state does not reflect updates made by the child component's successful dispatch of a reducer through Redux Toolkit

I encountered a strange issue where the state slice is behaving correctly (verified by unit tests and manual testing). However, it appears that the react selector is not properly subscribing to it. Here is the parent component code: import { useSelector } ...

JavaScript - Replacing key/value pairs in an object and transferring them to a different object

I am struggling with accessing and modifying the keys, values, and entries in an object (array), then transferring it to a new empty object (newArray). While I can retrieve the keys, values & entries, I'm facing difficulty making changes to them. The ...

Converting the structure of an object into an array structure for highcharts can be achieved through

I am looking to transform the object structure below: [ { "tahun": "2010", "apel": 100, "pisang": 200, "anggur": 300, "nanas": 400, "melon": 500 }, { ...

Get an MP4 on your iPhone (iOS) by downloading it from a link on a webpage

Despite trying various methods such as the HTML5 download tag, JavaScript, JQuery, and other techniques, I have not been able to successfully download a file to the Album. While photos can be saved by long clicking and selecting "Save Image", videos do n ...

jQuery UI Error: e.widget.extend cannot be used as a function

Recently, I made some changes to my jQuery files which now include jQUery UI for using the tooltip feature. However, I am facing an issue where Javascript is throwing the following error: TypeError: e.widget.extend is not a function Can someone provide ...

Experience interactive video playback by seamlessly transitioning a webpage video into a pop-up when clicking on an

I want to have a video play as a pop-up when the user clicks a play button, while also fading out the background of the page. It should be similar to the way it works on this website when you click to watch a video. How can I achieve this? <div class=" ...

Guide to generating dynamic arrays in JavaScript when a button is clicked

I am working on a JavaScript program where I dynamically generate buttons and div tags, as well as retrieve data from a local JSON file. My goal is to implement a new feature where clicking a button will create an array with the same name as the button, al ...