Issue
I have this below code where in I am trying to push 'No Data' in one of the index in array which doesn't have data.
data = ['a', 'b', '', 'd', 'e'];
onClick() {
this.data.forEach(element => {
if (element == '') {
element.push('No Data');
}
});
console.log(this.data);
}
But I am getting error as TypeError: element.push is not a function.
What is wrong in the code and is there any better ways to solve this?
Solution
Each element of your array is a string.
Strings don't have a push method and they cannot because they are immutable. That is you can't change the characters in a string.
This is trivially solved however, as follows:
this.data = this.data.map(d => d === '' ? 'No Data' : d);
What we've done here, is use Array.prototype.map to transform the array into a new array with all of the empty string elements replaced as per your specifications.
In context:
data = ['a', 'b', '', 'd', 'e'];
onClick() {
this.data = this.data.map(d => d === '' ? 'No Data' : d);
console.log(this.data);
}
Answered By - Aluan Haddad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.