forEach not changing values of array Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of forEach not changing values of array without wasting too much if your time.

The question is published on by Tutorial Guruji team.

availableButtons.forEach(function(part, index) {
    console.log(this[index].title)
    // this[index].title = intl.formatMessage(this[index].title);
  }, availableButtons)

The code above prints the console as follows:

{id: "abc.btn.xyz", defaultMessage: "someMessage"}

This confirms that each object has an id but when I try to execute the commented code it throws an error saying [@formatjs/intl] An id must be provided to format a message.

I used the same array but only a single object separately as follows intl.formatMessage(availableButtons[0].title); this gave me the required result I am just not able to figure out. I tried various ways of passing values in forEach, what am I missing?

Answer

I think Array#map works better for in this vade

availableButtons.map(part => {
    return {
    ...part,
    title: intl.formatMessage(part.title)
    };
});

We are here to answer your question about forEach not changing values of array - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji