0

Why does this not work (using Lodash map function):

const data1 = [{test:"test"}];
const data2 = _.map(data1, ((item) => {...item, id:1}));

But this does:

const data3 = [{test:"test"}];
const data4 = _.map(data3, ((item) => Object.assign({}, item, {id:1})));

And outside the map also works:

const data5 = {test:"test"};
const data6 = {...data5, id:1}
AndrewL64
  • 15,794
  • 8
  • 47
  • 79
CSharpAtl
  • 7,374
  • 8
  • 39
  • 53
  • You need to wrap your object into parenthesis, if you don't want to write a return statement. Like `=> ({...item, id:1})` – iagowp Dec 13 '18 at 17:20
  • [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508) – Felix Kling Dec 13 '18 at 18:06

4 Answers4

0

To return an object within a map, it needs to be wrapped in (). So when you do map((item) => {...item, id:1}) should be map((item) => ({...item, id:1}))

const data1 = [{test:"test"}];
const data2 = data1.map((item) => ({...item, id:1}));
console.log(data2);
José Salgado
  • 981
  • 10
  • 25
0

You just have the wrong syntax when it comes to returning an a "composed" object with ES6. If you are using arrow functions and need to return implicitly and object you need to wrap it with ():

Same with Array.map btw. Here is the example with ES6 since lodash in this case does not play a role really.

const data1 = [{test:"test"}];
const data2 = data1.map(item => ({...item, id:1}));

console.log(data2)

Rest is using an Object.assign to do the object merge for you and return it and last is just an object literal.

Akrion
  • 18,117
  • 1
  • 34
  • 54
0

In this line const data2 = _.map(data1, ((item) => {...item, id:1})); Not putting () around the return value makes the interpreter think you are opening a block with those {}

Try changing it to const data2 = _.map(data1, ((item) => ({...item, id:1})));

ack_inc
  • 1,015
  • 7
  • 13
-1

In case of object literal you need to do like this

When you use { it is interpreted as starting braces of function than you need to use return.

=>{...item, id:1} here the { is interpreted as starting brace of function so spread operator will throw a error.

const data1 = [{test:"test"}];
const data2 = data1.map((item) => {return{...item, id:1}});
console.log(data2);

P.S For the down voters who think answer is not given using loadash

const data1 = [{test:"test"}];
const data2 = _.map(data1, ((item) => {return {...item, id:1}}));
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • I didn't vote down, but I think you are not using Loadash, OP's is asking for loadash map. – carkod Dec 13 '18 at 17:20
  • @carkod well this answer will be applicable whether you use loadash or not. i tried to explain concept. anywayns problem – Code Maniac Dec 13 '18 at 17:24