简体   繁体   中英

Trying to combine a .forEach and a .map function but I get return undefined

I have the following .map function that creates a new array of elements and changes their selected property to false:

const newAlteredData = alteredData.map((element) => {
  return { ...element, selected: false };
});

However, now I want to only change the elements that also exist in another array called changeRows

I tried the following:

const newAlteredData = alteredData.map((element) => {
  changeRows.forEach((changeRow) => {
    if (changeRow.deviceId === element.deviceId) {
      return { ...element, selected: false };
    }
    return element;
  });
});

However, this just return an array of undefined. Am I not using.map and/or.forEach correctly here?

Am I not using.map and/or.forEach correctly here?

forEach() is NOT the right method to use here. It is meant for iterating over an array - not finding elements inside it.

forEach() method doesn't not returns anything. Any value returned from its callback function is ignored.

Javascript provides multiple methods to find an element inside an array. You can use the find method to find an element in the changeRows array.

const newAlteredData = alteredData.map((element) => {
   const exists = changeRows.find(el => el.deviceId === element.deviceId);
 
   if (exists) {
      return { ...element, selected: false };
   }
});

Other methods that can be used:

As @sirius mentioned you forgot to return something from the forEach .

I would fix it this way:

const newAlteredData = alteredData.map((element) => {
  const arr = []
  changeRows.forEach((changeRow) => {
    if (changeRow.deviceId === element.deviceId) {
      arr.push({ ...element, selected: false });
    }
    arr.push(element);
  });
  return arr
});

You can not return any thing inside a forEach .

Change this:

const newAlteredData = alteredData.map((element) => {
  changeRows.forEach((changeRow) => {
    if (changeRow.deviceId === element.deviceId) {
      return { ...element, selected: false };
    }
    return element;
  });
});

TO

const newAlteredData = alteredData.map((element) => {
  changeRows.find(changeRow => changeRow.deviceId === element.deviceId) {
     return { ...element, selected: false };
  }
  return element;
});

forEach don't return anything in javascript.

You can use filter to achieve what you want and map through only the existing elements.

const newAlteredData = alteredData.filter(
  element => changeRows.find(
      changeRow => changeRow.deviceId === element.deviceId
    )
  ).map((element) => {
  return { ...element, selected: false };
});

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