简体   繁体   中英

forEach with spread operator returns undefined

I have an array of object of this type:

[{id: "somethin%g", apple: "dfgdf efd"}, ...]

I want to replace some special chars in values of key = id and not change anything else of the object.

So the example above, must be:

[{id: "something", apple: "dfgdf efd"}, ...]

I try this function:

function removeSpecialCharacters(metadata) {
  const result = metadata.forEach(datum => {
    const cleanId = datum.id.replace(/[.|&;$%@%"<>+]/g, '')
    return { ...datum, id: cleanId }
  })
  console.log(result)
  return result
}

I get result = undefined . Why?

You have to replace the forEach by a map . forEach does not return an array. It simply runs the content of the loop and discards the results. Whereas map will create a second array and fill it with the mapped content.

 function removeSpecialCharacters(metadata) { const result = metadata.map(datum => { const cleanId = datum.id.replace(/[.|&;$%@%"<>+]/g, '') return { ...datum, id: cleanId } }) return result } const data = [{id: "somethin%g", apple: "dfgdf efd"}]; console.log(removeSpecialCharacters(data)); 

Here is a shorter way to do this:

 function removeSpecialCharacters(metadata) { return metadata.map(datum => ({ ...datum, id: datum.id.replace(/[.|&;$%@%"<>+]/g, '') }) ) } const data = [{id: "somethin%g", apple: "dfgdf efd"}]; console.log(removeSpecialCharacters(data)); 

See the doc on map and forEach on MDN.

Because the return value of forEach is undefined ( MDN ). Use Array.prototype.map() instead

Also, if you want only alphanumeric characters in your id , you could simply use this regex: \\W+

\\W+ matches all the non-alphanumeric characters. Replace them with empty string.

 function removeSpecialCharacters(metadata) { const result = metadata.map(datum => { const cleanId = datum.id.replace(/\\W+/g, '') return { ...datum, id: cleanId } }) return result } const data = [{id: "someth+in%g#", apple: "dfgdf efd"}, {id: 'some%@%"<>+#', apple: "dfgdf efd"}]; console.log(removeSpecialCharacters(data)); 

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