简体   繁体   中英

TypeScript/JavaScript array value push

I have this objet : keyValue : { key : string , value : number}[];

I want to add a new element to this array from two values, like this :

 let tmpTabKV : { key : string , value : number}[];
 [...]
 tmpTabKV.push({projet.libelle, statKV.value});
 [...]
 keyValue  = tmpTabKV;

I tried multiple syntaxes and seen this : How can I add a key/value pair to a JavaScript object?

But I don't see any key to create a new object. The usage of an Array makes me an error

tmpTabKV.push(Array(projet.libelle, statKV.value));

You should be pushing an object literal to your array

let tmpTabKV : { key : string , value : number}[] = []
tmpTabKV.push({key:projet.libelle, value:statKV.value});

According to let tmpTabKV : { key : string , value : number}[]; just do :

tmpTabKV.push({key: project.libelle, value: statKV.value})

but I think you want this :

tmpTabKV.push({[project.libelle]: statKV.value})

A few problems I've noticed: first, you're pushing a new object to the array as if it was itself an array. That is, you're relying on position of the values to map to the position of the keys. In an object, the keys are always unordered and therefore must always be specified.

tmpTabKV.push({key: project.libelle, value: statKV.value})

What you're doing with {project.libelle, startKV.value} is making an object with shorthand syntax , which would not work in your example.

In typescript, if you want to restrict the keys in an object, implement an interface.

interface KeyValue { key: string, value: number }

let tmpTabKV: KeyValue[];

// ...

tmpTabKV.push({key: project.libelle, value: number});

you should push a new object:

interface KeyValuePair{
   key: string:
   value: number;
}

let tmpTabKV: KeyValuePair[];

tmpTabKV.push(new {key: projet.libelle, value: statKV.value});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM