1

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?

1
  • It is interpreting the {} as a block not an object. Wrap the curly braces in parens. (This is only one of the things stopping this working) Commented Oct 19, 2017 at 8:05

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.