[英]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.