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));
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));
Share
Improve this question
edited May 23, 2017 at 11:46
CommunityBot
11 silver badge
asked Feb 20, 2017 at 14:55
CallehabanaCallehabana
952 silver badges14 bronze badges
0
4 Answers
Reset to default 6You 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});