Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing items to an array in typescript with key value

I would like to push an array to another array but the result generates an incorrect result

let pusheditems:any[]  = [];
pusheditems.push(this.yesvalue);
pusheditems.push(this.selectedtruck);

Later when i console.log(pusheditems)

Am getting an array of type

array(0->yes array, 1->select truck array)

What am looking for is to change the index values of 0,1 to strings like yes, truck

So i would expect to get

array(yes->yes array, truck->select truck array)

I have also tried

pusheditems.push({yes:this.yesvalue});  //adding yes
pusheditems.push({truck:this.selectedtruck}); //adding truck

But this doesnt work

The values of

this.yesvalues and this.selectedtruck are also arrays

What do i need to add further

like image 901
Geoff Avatar asked Feb 24 '17 14:02

Geoff


People also ask

How do you push a key value pair to an array?

Use reduce() to Push Key-Value Pair Into an Array in JavaScript. The reducer function got executed by the reduce() method. It returns only one value, and that is the accumulated answer of the function.

Can you push object to array TypeScript?

To push an object to an array: Set the type of the array to Type[] . Set the type of the object to Type . Use the push() method to push the object to the array.

How do you push an object to an array of arrays?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.


2 Answers

In Typescript, arrays can have keys only of type number. You need to use Dictionary object, like:

    let pusheditems: { [id: string]: any; } = {};    // dictionary with key of string, and values of type any
    pusheditems[this.yesvalue] = this.selectedtruck; // add item to dictionary
like image 183
Petr Adam Avatar answered Nov 26 '22 10:11

Petr Adam


Thing you are trying to achieve is to create object, not an array.

You can do it:

let pusheditems = {};
pusheditems[this.yesvalue] = this.selectedtruck;
like image 34
Igor Janković Avatar answered Nov 26 '22 09:11

Igor Janković