admin管理员组文章数量:1356243
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});
本文标签: TypeScriptJavaScript array value pushStack Overflow
版权声明:本文标题:TypeScriptJavaScript array value push - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744035435a2579685.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论