从for循环填充对象列表的简写方法

时间:2018-06-01 10:25:53

标签: javascript

我目前正在使用以下内容使用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代码段?

2 个答案:

答案 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)

使用Array.map



const foo = ['bar', 'hello', 'world']

const things = foo.map((name) => {return {name, age:1}});
console.log(things);




相关问题