Softcore
Softcore

Reputation: 95

how to pass a new value into a newly created object in typescript

I am using Angular 6 an working with arrays. I have an array and a model.

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"
    },
]

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;
    }
}

As you see there is a parameter in the model named "index". When an item is selected from this array, I create a new object with this method.

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

As expected the result is:

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

In this case I can't add the index value into the newly created object because data object doesn't have this parameter.

That's why I use

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

My question is: Is there a way for adding additional parameters while creating a new object with models. I need something like this.

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

Upvotes: 0

Views: 920

Answers (2)

Macro
Macro

Reputation: 51

You cant create a new object Data in the class Data. You can try this:

export interface IData {
     index: number;
     id:number;
     value:string;
     description:string
}

selectItem(index, data):IData{
    let result:IData = {
       index: index,
       id: this.id, 
       value: this.value, 
       description: this.description
    };
    return result;
}

Upvotes: 0

Eliott Robson
Eliott Robson

Reputation: 980

I would create an optional parameter for your constructor.

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;
  }
}

And then later on you can do exactly as you need

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

But it's also possible to create an object without it if you need

let selectedItem = new Data(data);

Upvotes: 3

Related Questions