0

in the below code, activeProgs is an array contains program objects. i am using .map because i would like to have an array containing the name of the program and a token value. this token value is an integer and it could be incremented by one for each program as shown below in the code.

my question is, if i want to have the same array that contains the program name and the token but as an object. in other words, i want the .map() to return an array but that array contains objects with two attributes "progName" and "token". can i do the following?

    activeProgs.map((prog)=> {progName: prog.getHeader().getName(), token: (++i)} )

please let me know how to do it correctly

code:

activeProgs.map((prog)=> prog.getHeader().getName() + '->' + (++i))
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • Please share sample input and output. You might need this `activeProgs.map((prog)=> ({progName: prog.getHeader().getName(), token: (++i)}) )` – Hassan Imam Jun 27 '18 at 07:13
  • is this `var arrayofObject = activeProgs.map((prog)=> {progName: prog.getHeader().getName(), token: (++i)} )` return an array of object? right – Aravind S Jun 27 '18 at 07:15
  • @HassanImam, comments are not for answers, which is why i said the same thing as an answer haha ;) – coagmano Jun 27 '18 at 07:16

2 Answers2

1

like so:

activeProgs.map((prog) => ({progName: prog.getHeader().getName(), token: (++i)}) );

or like so:

activeProgs.map((prog) => {
    return {progName: prog.getHeader().getName(), token: (++i)} 
})

In the first example, adding brackets around the {} forces it to be parsed as an expression containing an object literal. In your code, it is interpreted as part of the function declaration, making the next bit a syntax error.

The second one makes that more explicit

coagmano
  • 5,542
  • 1
  • 28
  • 41
0

You weren't far off with the example you suggested, you just needed to wrap the object in brackets so the compiler understands you are returning an object and not declaring a function body

activeProgs.map(prog => ({
  progName: prog.getHeader().getName(),
  token: (++i)
}))
James
  • 80,725
  • 18
  • 167
  • 237