Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing value in an Array in typescript

I have an Array localData defined as:

public localData: Array<any> = [];

In the sample below it has length of 2 and following values in developer tools.

(2) [{…}, {…}]
0:
Country: "United States"
DataSource: ""
FunctionName: "Customer Service"
GroupName: "Main"
Index: 0
Result: undefined
StartDate: "5/1/2012"
StopDate: "
"
1:
Country: "United States"
DataSource: ""
FunctionName: "Customer Service"
GroupName: "Main"
Index: 1
Result: undefined
StartDate: ""
StopDate: "5/1/2019
"
__proto__: Object
length: 2
__proto__: Array(0)  

I need to replace the DataSource value to, if blank or if it has any other value then, to a certain value. I tried doing:

 this.localData.forEach(x => x.DataSource ? '' || 'XXX' : 'MyVAL');

This code doesn't throw any error but DataSource still remains blank. Has anyone had this issue before, or knows why this is happening?

like image 328
SilverFish Avatar asked Aug 23 '26 03:08

SilverFish


2 Answers

You're not using assignment. As Doc explains, forEach run the provided function for each element, and your function simply return a boolean if x.DataSource exist, a string otherwise.

If your goal is to change your array you can either modify your function with an assignment:

this.localData.forEach(x =>  {
   x.DataSource = x.DataSource ? '' || 'XXX' : 'MyVAL'
});

or simply use the map function

this.localData = this.localData.map( item => {
   item.DataSource = item.DataSource ? '' || 'XXX' : 'MyVAL'
   return item;
});

Clarification: in your code line

this.localData.forEach(x => x.DataSource ? '' || 'XXX' : 'MyVAL');

the ternary operator is gonna return 'MyVAL' if x.DataSource is undefined or the empty string, and always 'XXX' if all the other cases. If i get it right, you want to do something like:

x.DataSource && x.DataSource !== 'XXX' ? 'MyVAL' : x.DataSource;

which can be read as: if DataSource is evaluated and it's different from 'XXX' assign 'MyVal', keep it as it is otherwise.

EDIT: clarification

like image 141
Koop4 Avatar answered Aug 25 '26 18:08

Koop4


try following way:

this.localData.forEach(x => (!x.DataSource || x.DataSource === 'XXX') ? 'MyVAL' : x.DataSource);

Where

!x.DataSource means x.DataSource === ''

like image 23
Mariano Calcagno Avatar answered Aug 25 '26 18:08

Mariano Calcagno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!