DDave
DDave

Reputation: 1543

js map why is not changing my value with return

I'm doing map with a variable, and doing a return to change his value, but it's not working, the value for the whole array is the same:

  //resultValues = processValues(table,resultValues,'toClient');
  resultValues.map ( (record) => {
    record = processValues(table,record,'toClient');
    return record;
  });
  return Promise.resolve(resultValues);  // does  not change

so I had to create another variable to be able to have a change on the array. why is this behavoiur? it's normal in map ?; is there another option with lodash by example to don't need create a second variable?

  let newResult = [];
  resultValues.map ( (record) => {
    record = processValues(table,record,'toClient');
    newResult.push(record);   // with this changes are sent to new var
    //return record;
  });
  // return Promise.resolve(resultValues);
  return Promise.resolve(newResult);

Upvotes: 0

Views: 463

Answers (2)

Faly
Faly

Reputation: 13356

Array.map returns a new array instance where each element inside it is transformed:

let ret = resultValues.map (record => processValues(table,record,'toClient'));
return Promise.resolve(ret);

Upvotes: 4

anon
anon

Reputation:

Map returns a new array. You could literally do:

const newArr = resultValues.map ( (record) => {
  record = processValues(table,record,'toClient');
  return record;
});

Please read the first sentence of the MDN web docs for map().

Upvotes: 0

Related Questions