tnkh
tnkh

Reputation: 1829

array.map iterates over an array to return an object array

Suppose I would like to turn an array of

let originalArray = [a,b,c]

into an array of such format:

[{0:a},{1:b},{2:c}] 

I was using map function to iterate over the originalArray as such

originalArray.map((val, i) => {i:val})

However it returns all undefined values. My question is how can I use map function to achieve my intended result?

Upvotes: 1

Views: 54

Answers (2)

bitifet
bitifet

Reputation: 3659

Your arrow function is syntactically incorrect because, in that context, { and } are interpreted as block delimiters:

(val, i) => {i:val} // Here '{' and '}' are a block delimiters.

You need to, at least, enclose it between parentheses to force it to be interpreted as object expression:

(val, i) => ({[i]:val}) // This works.
// Also notice the '[' and ']' surrounding "i" meaning that the
// value of i should be used as key instead of actual "i".

Think about this:

(val, i) => {i, val}

...What it is supposed to return? {i:<i_value>, val:<val_value>} or undefined (because i, val evaluates to val value, but while enclosed in block delimiters, you need to explicitly user 'return' statement:

$ node
> let f = (x)=>{x+1}
undefined
> f(3)
undefined
> let f = (x)=>{return x+1}
undefined
> f(3)
4

Alternatively you could do something like this, but, in this case the use of arrow function would become pointless IMHO:

(val, i) => {return {i:val}}

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68635

You need to use [] notation for the property name to evaluate the expression and use the value under it. Also wrap your returned object with () brackets, without this the compiler understands the starting { of the object as the arrow functions body start and gives wrong result.

let originalArray = ['a','b','c'];
let mappedArray = originalArray.map( (item, index) => ({[index]: item}));

console.log(mappedArray);

Your code snippet is like this one, which, if you don't explicitly return anything, it by default returns undefined.

let originalArray = ['a','b','c'];
let mappedArray = originalArray.map( (item, index) => {
    index: item;
    return undefined;
});

console.log(mappedArray);

Upvotes: 3

Related Questions