0
let x = {a:1,b:2,c:3}
let result = Object.keys(x).map((i) => {
  console.log(i) ;
  return ({i :x[i]});
})

why result is

[{i: 1},{i: 2},{i: 3}]

? In console, value of i i.e a,b,c is being printed. What happens during return?

4
  • 1
    what is x in your code ? Commented Oct 5, 2019 at 9:14
  • 1
    The code above does return an array of objects. What makes you think it doesn't? Also, what's x? Commented Oct 5, 2019 at 9:14
  • 1
    If you want to use value of your variable as a property of object you should use square brackets [i] Commented Oct 5, 2019 at 9:19
  • 1
    Your question was answered Commented Oct 5, 2019 at 9:33

1 Answer 1

3

Why map method does not return array of object?

It does.

What happens during return?

The return ({i :x[i]}); line means:

  • Create an object.
  • Give it a property called "i" (not the value of i, the actual literal name "i") with the value from x[i].
  • Return that as the value for this map iteration, which will be used in the result array.

The result is an array of objects, each with one property called "i".

If you meant to use the value of i, you'd need to use a computed property name. There's also no reason for the () around the object literal:

return {[i]: x[i]};
//      ^^^------------- computed property name

Live Example:

let x = {a:1,b:2,c:3};
let result = Object.keys(x).map((i) => {
  console.log(i) ;
  return {[i]: x[i]};
});
console.log(result);
.as-console-wrapper {
    max-height: 100% !important;
}

This was introduced in ES2015. In ES5 and earlier, you'd have to create the object first, then add the property to it afterward.

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

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.