我目前正在使用以下内容使用for
循环填充对象列表:
const foo = ['bar', 'hello', 'world']
const things = []
foo.forEach((x) => {
things.push({
name: x,
age: 1
})
})
这让我觉得有点费解。在Python中,列表理解的概念允许我这样做:
foo = ['bar', 'hello', 'world']
things = [{name: x, age:1} for x in foo]
JavaScript中是否有相同的内容?是否有更好的方式来填充things
而不是我的JavaScript代码段?
答案 0 :(得分:5)
您可以使用Array#map
映射对象,并为name
获取short hand property。
const
foo = ['bar', 'hello', 'world'],
things = foo.map(name => ({ name, age: 1 }));
console.log(things);
答案 1 :(得分:4)
const foo = ['bar', 'hello', 'world']
const things = foo.map((name) => {return {name, age:1}});
console.log(things);