使用map方法将javascript对象数组转换为其他对象的数组[duplicate]

时间:2022-01-26 11:58:21

This question already has an answer here:

这个问题在这里已有答案:

I want to convert one array to another kind of array. Actually I am using typescript. What am I doing wrong here:

我想将一个数组转换为另一种数组。其实我正在使用打字稿。我在这做错了什么:

//terminals is an array of objects. 
    groupOptions = terminals.map(trm => {
                id: trm.TerminalID, 
                text: trm.TerminalName, 
                selected: true
            });

intelisence complains about the body of the curly brackets. With them I meant an object, probably intellisence thinks its anonymous method body. How can I workaround this?

知识分子抱怨大括号的主体。有了它们,我的意思是一个对象,可能是intellisence认为它的匿名方法体。我该如何解决这个问题?

1 个解决方案

#1


2  

Try wrapping the curly brackets with parenthesis like this:

尝试用括号括起大括号,如下所示:

    //terminals is an array of objects. 
    groupOptions = terminals.map(trm => ({
                id: trm.TerminalID, 
                text: trm.TerminalName, 
                selected: true
            }) );

Problem is that the JavaScript runtime picks up the curly brackets as beginning/end of a function.

问题是JavaScript运行时选择大括号作为函数的开头/结尾。

#1


2  

Try wrapping the curly brackets with parenthesis like this:

尝试用括号括起大括号,如下所示:

    //terminals is an array of objects. 
    groupOptions = terminals.map(trm => ({
                id: trm.TerminalID, 
                text: trm.TerminalName, 
                selected: true
            }) );

Problem is that the JavaScript runtime picks up the curly brackets as beginning/end of a function.

问题是JavaScript运行时选择大括号作为函数的开头/结尾。