简体   繁体   English

TypeScript / JavaScript数组值推送

[英]TypeScript/JavaScript array value push

I have this objet : keyValue : { key : string , value : number}[]; 我有这个对象: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? 我尝试了多种语法,然后看到了这一点: 如何将键/值对添加到JavaScript对象?

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}[]; 根据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. 您使用{project.libelle, startKV.value}所做的事情是使用速记语法创建一个对象,该语法在您的示例中不起作用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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