最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to create a list of objects in Typescript in one line - Stack Overflow

programmeradmin1浏览0评论

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:

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

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:

result = [{"value": each} for each in values]
Share Improve this question asked Jul 14, 2021 at 3:54 alphanumericalphanumeric 19.4k74 gold badges277 silver badges421 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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 puted property names:

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

发布评论

评论列表(0)

  1. 暂无评论