2

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments