简体   繁体   中英

JavaScript: Create Object given .map() input arguments without using ES6 {} Shortcut

I am currently using JavaScript ES6 to create the following output object from a .map array method.

const indexAndValue = (arr) => {

  return arr.map((elem, index) => {
    return { index, elem }
  }); 
}

indexAndValue([22, 33, 44, 55])

The output code is:

[ { index: 0, elem: 22 },
  { index: 1, elem: 33 },
  { index: 2, elem: 44 },
  { index: 3, elem: 55 } ]

How do I get the same output without using the {} shortcut? I tried the following code:

const indexAndValue = (arr) => {

  let obj = {}; 

  return arr.map((elem, index) => {
    return obj[index] = elem; 
  }); 
}

indexAndValue([22, 33, 44, 55])

This code returns incorrectly:

[ 22, 33, 44, 55 ]

You need to move the declaration of object inside of the callback. If outside, you reuse the object and all elements contains the same object, with the latest update, because of the same object reference.

 const indexAndValue = (arr) => { return arr.map((elem, index) => { var object = {}; object.index = index; object.elem = elem; return object; }); } console.log(indexAndValue([22, 33, 44, 55]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM