简体   繁体   English

如何在一行中创建 Typescript 中的对象列表

[英]How to create a list of objects in Typescript in one line

I have a list of values我有一个值列表

let values = ["value-01", "value-02"]

I go ahead and turn them into the list of objects:我继续将它们转换为对象列表:

let result = [];
for (let each of values) { 
  result.push({ value: each });    
};

console.log(result)

which logs哪些日志

[ { value: 'value-01' }, { value: 'value-02' } ]

I wonder if there is a shorter way to achieve this?我想知道是否有更短的方法来实现这一目标? In Python I could do it in a single line like so:在 Python 中,我可以像这样在一行中完成:

result = [{"value": each} for each in values]

It's a pretty simple mapping.这是一个非常简单的映射。

 let values = ["value-01", "value-02"]; const result = values.map(value => ({ value })); console.log(result);

While there is nothing wrong with using a for loop, you could make use of this code using map() , split() and computed property names:虽然使用 for 循环没有任何问题,但您可以使用map()split()和计算属性名称来使用此代码:

 let values = ["value-01", "value-02"]; let ans = values.map((a) => ({ [a.split('-')[0]] : a })) console.log(ans);

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

相关问题 如何在 SailsJS 中创建与另一个模型的对象单向关联的对象列表? - How to create a list of objects which are one-way associated with objects of another model in SailsJS? 如何在 JavaScript 中创建对象列表 - How to create a list of objects in JavaScript 如何在javascript中创建对象列表 - how to create list of objects in javascript 如何在不丢失TypeScript类属性的情况下将JSON对象列表转换为TypeScript对象列表? - How do I cast a list of JSON objects into a list of TypeScript objects without losing properties on the TypeScript class? 如何获取对象列表并创建列表中对象特定属性的JSON? - How to take a list of Objects and create a JSON of specific properties of the objects in the list? Typescript如何使用映射类型创建嵌套的接口对象? - Typescript how to create a nested interface objects using mapped types? 如何从 typescript 中的对象列表数组中打印叶节点? - How to print the leaf nodes from an array of list of objects in typescript? 如何遍历 Typescript 中具有数组和对象的大型数组列表 - How to traverse large array list having array and Objects in Typescript Typescript:如何按字段名称对命名对象列表的 object 进行分组 - Typescript : How to group an object of named list of objects by field name 将对象添加到angular 2打字稿中的列表 - Adding objects to a list in angular 2 typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM