React JS array forEach get refs value using variable - reactjs

How can i get this to work correctly using this method below? I need to go through each value in the array
array.forEach((v) => {
let a = `this.refs.a${v}.value`
console.log(a) // prints this.refs.a0.value
console.log(this.refs.a0.value) // prints correct value
})

I assume you are trying to access refs by name. In JavaScript you can access object's property using object[propertyName] syntax, where the property name is a string.
Using this method you can rewrite your property access to this.refs[`a${v}`].value.
So the final code should look like this:
array.forEach((v) => {
let r = this.refs[`a${v}`].value
console.log(r) // prints correct value
})

Related

How sort this json format in react native using map function

I have the following JSON format
{
"name":"xyz",
"age-group":"bb"
}
How to get sort out this JSON
I use the following code
const array = [{ "name":"xyz", "age-group":"bb"} ]
array.map((element) => {
Console.log(element.age-group)
});
I got an error:
Can't find variable: group
1st thing is you can't map object.
and in your case you set json object in array and then you are maping it.
so it must be like:
array[0].name;
but in second property, it has hyphen which looks like "age-group" to access object property containing hyphen is:
array[0].obj["age-group"] //this is return `bb`
so in your code it will be:
array.map((element) => {
console.log(element.obj["age-group"])
});
to access object property with hyphen(-) you need to use notation with square brackets.

Best approach in moving data from one array to a new array in angular ts

.subscribe((dataChart) => {
// console.log(dataChart)
var forxaxis = []
var cd = [dataChart]
// console.log(cd)
cd.forEach(element => {
forxaxis.push(element.strRequestDate)
console.log(forxaxis)
});
},
Im trying to move my data in the first array into a new array so that I can use it with chart.js. but it didnt work.
dataChart contain 2 column of data. i insert dataChart into an array called cd. then i tried to push one of the column from dataChart which is called strRequestDate into a new array called forxaxis but it just didnt work as per expected. the result is as shown in the image attached.
this is how the data look like. it was called by using sharepoint API
error and the data
You can use array.map property here, so you don't need to push data manually from one array to another
I have taken sample data in dataChart array for demonstration purpose only.
let dataChart = [{strRequestId: 1, strRequestDate: 'ABC'}, {strRequestId: 1, strRequestDate: 'PQR'}];
let forxaxis = dataChart.map(x => x.strRequestDate);
console.log(forxaxis);
Demo
Output:

React JS .map and assignment causing esLint error 'Assignment to property of function parameter. eslint(no param-reassign)'

I am trying to figure out how to fix a esLint error of the following
'Assignment to property of function parameter. eslint(no param-reassign)'
Here is my code so far
myArray.records.map(record =>
record.subRecords.map(subRecord => (
subRecord.transId = this.getIdCorrection(subRecord.transId)
))
))
I tried using cloneDeep and making another copy for map and reassign, the error is there there.
I read a few post but I am confused with how they are using filter.
I am pass an integer value and it passes an integer based on some business rules.
I am not sure how to get pass this one.
Thanks
ESLint probably wants you to create and return a new object. Remember that map isn't for mutating the elements of an array, it's for creating a new array of items.
const newRecords = myArray.records.map(record => ({
...record,
subRecords: record.subRecords.map(subRecord => ({
...subRecord,
transId: this.getIdCorrection(subRecord.transId)
})
}))

Problems with parsing a JSON Array after retrieving from firebase when using ionic-selectable

I'm currently developing an App using Ionic 3 and Firebase. I'm using ionic-selectable (you can see my stackblitz here) for the user to select an option from my firebase database array and return the selected option to the user's id.
I have got everything to work, except that ionic-selectable is not reading the retrieved array form firebase.
I'm retrieving the array using the following code:
this.itemsRefdiag = afg.list('medicalhx');
this.items = this.itemsRefdiag.snapshotChanges().map(changes => {
return changes.map(c => ({ ...c.payload.val() }));
});
const dgRef = this.afg.database.ref();
dgRef.child('medicalhx').orderByChild('name').on('value', snapshot => { this.snapshot2 = JSON.stringify(snapshot).replace(/"[0-9]":{"name":|{|}/g, ""); })
My console.log results in:
"Hyperthyroidism","Hypothyroidism","Diabetes Type 1","Diabetes Type 2"
However, when using ionic-selectable for private diagnoses: Diagnosis[] = [this.snapshot2], I get 'undefined' options. However, when I manually type in private diagnoses: Diagnosis[] = ["Hyperthyroidism","Hypothyroidism","Diabetes Type 1","Diabetes Type 2"], it works. I also tried parsing the JSON array using the following code instead:
this.itemsRefdiag = afg.list('medicalhx');
this.items = this.itemsRefdiag.snapshotChanges().map(changes => {
return changes.map(c => ({ ...c.payload.val() }));
});
const dbRef = this.afg.database.ref();
dbRef.child('medicalhx').orderByChild('name').on('value', snapshot =>
{ let snapshot3 = JSON.stringify(snapshot).replace(/"}/g, `"`);
let snapshot4 = snapshot3.replace(/"[0-9]":{"name":|{|}|"/g, "");
this.snapshot2 = snapshot4.split(",");
});
My console.log results in an Object with separate strings (an array):
["Hyperthyroidism","Hypothyroidism","Diabetes Type 1","Diabetes Type 2"]
However, ionic-selectable still doesn't seem to read that and I get undefined error. Any ideas on what I may be doing wrong with the array?
EDIT
It actually does work the second time around, however the console error pops up the first time and I believe this is because it's not waiting for the array results to pop-up the first time around. Is there a way to add a wait time until the array loads?
The second code listed in the question converting it to a real array worked but required a loading time, hence poping up a console error. I managed to get around the loading time issue by implementing Asynchronous searching as per this stackblitz.

Display content of an Array of Objects with Interpolation in Angular2 Typescript

Application
A simple Search bar and a button where user enters a keyword and the response returned is from a RESTful server (HTTP GET requests)
simplesearch.ts
export class SimpleSearch {
kw: string; // keyword
resp: string; // response from Server
}
simplesearch.service.ts
Has a simple method called searchData which does a HTTP GET request with the user's keyword as a query search. (Code not included for brevity)
simplesearch.component.ts
/*All respective headers and #Component removed from brevity*/
const OUTPUT: SimpleSearch[] = []; // create an array for storing Objects
export class SimpleSearchComponent {
Output = OUTPUT; // define variable for array
constructor(private httpServ: SimpleSearchService, private temp: SimpleSearch) {}
/*Search button on HTML file does this*/
Search(inputVal: string) {
this.temp.kw = inputVal; // store the value of user's input
this.httpServ.searchData(inputVal)
.then(res => this.temp.resp = res); // store the response in temp.resp
// push the Object on the Output Array
this.Output.push({kw: this.temp.kw, resp: this.temp.resp});
}
}
Interpolation Variable
I use Output as an Interpolation Variable for my HTML template. I show the data in an unordered list
<ul>
<li *ngFor="let keyword of Output">
<span>{{keyword.kw}}</span>
</li>
</ul>
Response:
<ul>
<li *ngFor="let answer of Output">
<span>{{answer.resp}}</span> <!-- WHAT TO DO HERE for Array Index-->
</li>
</ul>
Result
I can see the keywords in a list every time a user inputs new keywords but
the responses in the wrong way
How do I pass Indexing with the Interpolation? Or am I thinking wrong?
The easy way out was to create two separate Array<String> for keywords and responses and this works great since I can use the index to delete the contents on the page too but with an Object in an Array I am confused with the key: value representation and the index of the Array (OUTPUT) itself.
The problem lies exactly where developer noticed, this.temp.resp is outside the async function. So when you are pushing items in your Output array, it's always pushing the previous search with the new keyword, therefore you are getting the behavior that the resp is always "one step behind". You can check this to understand this async behavior: How do I return the response from an Observable/http/async call in angular2?
So let's look at the code and explain what is happening. I assume you have initialized 'temp' since it isn't throwing an error on first search, where temp.resp would be undefined unless temp is initialized.
this.httpServ.searchData(inputVal)
// this takes some time to execute, so the code below this is executed before 'this.temp.resp' has received a (new) value.
.then(res => this.temp.resp = res);
// old value of 'temp.resp' will be pushed, or if it's a first search, empty value will be pushed
this.Output.push({kw: this.temp.kw, resp: this.temp.resp});
So how to solve this, would be to move the this.Output.push(... line inside the callback (then), so that the correct values will be pushed to the array.
Also I'd change your model to be an Interface instead of Class. But as to how to change the function and do the assignment inside the callback, I'd also shorten the code a bit and do:
Search(inputVal: string) {
this.httpServ.searchData(inputVal)
.then(res => {
// we are pushing values inside callback now, so we have correct values!
// and 'SimpleSearch' stands for the interface
this.Output.push(<SimpleSearch>{kw: inputVal, resp: res});
});
}
}
This should take care of it that the corresponding keyword will have the corresponding response! :)
PS. Worth noticing here, is that you'd maybe want to display the keyword while we are waiting for the response for that keyword, I ignored it here though and applied the same as you are currently using.

Resources