How to use spread operator? - reactjs

I am working on React JS. I am trying to use spread operator here. Below is my code.
const parametersQuickStoreSearch = (searchTerms, options, store) => {
}
In the above code value of searchTerms is simsKeycode:"35431081" and value of store is {value:all,label:all}. I want to combine the value of searchTerms and store as below.
{ simsKeycode:"35431081", store: store.value }
I tried as below
const storeParam = {
'store': store.value,
}
This line throwing me error Unnecessarily quoted property 'store' found
Can someone help me to complete this? Any help would be appreciated.

Below is the example :
const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };
const summary = {...person, ...tools};
/*
Object {
"computer": "Mac",
"editor": "Atom",
"gender": "Male",
"name": "David Walsh",
}
*/

You can try Object.assign
var searchTerms = {"simsKeycode":"35431081"}
var store = {"value":"all","label":"all"}
Object.assign({}, searchTerms, {store:store.value})
or spread operator
var searchTerms = {"simsKeycode":"35431081"}
var store = {"value":"all","label":"all"}
var storeParam = {store:store.value}
{...searchTerms, ...storeParam}
output:
"{"simsKeycode":"35431081","store":"all"}"

Related

Error: Response is not a function, when trying to find if the name exists

So I'm using mongodb to fetch some data from the database.
The issue is when I try to check for something in an array
Here is what the structure looks like:
Example array structure
{ // ...
likedPeople: [
{
name: "foo"
image: "test",
},
{
name: "bar",
image: "baz",
}
]
}
This is the array i get Back.
So when i try to find if it includes a certain value,
eg:
const displayName = "foo";
console.log(
likedPeople.map((likedPerson) => {
return likedPerson.name === displayName; // Output: [true, false]
})
);
But then If i again try to do some other method on it like map() or includes(), It breaks the setup:
const response = likedPerson.name === displayName; // Output: [true, false]
response.map((res) => console.log(res)); // Output: ERROR: response.map() is not a function
But the fact is that I am getting an array with the values, so what am I even doing wrong here?
I tried adding an optional chaining response?.map() but still it gave me the same error.
Also the includes() method also returns me the same response.includes is not a function error.
Can anyone help?
Use the some method to check the name exists in likedPeople :
const likedPeople = [
{
name: "foo",
image: "test",
},
{
name: "bar",
image: "baz",
}
];
const displayName = "foo";
const isExist = likedPeople.some(people => people.name === displayName);
console.log(isExist)

How to reset navigation.params object data

This is my code
{
key: "id-16263358905-23",
params: { "3067": 1 },
routeName: "Details"
};
I want to "params":{} ==>
{
key: "id-16263358905-23",
params: {},
routeName: "Details"
};
Please, help me
let obj = {"key": "id-16263358905-23", "params": {"3067": 1}, "routeName": "Details"}
let newObj = {...obj,params:{}}
you can do this, but over here the main question is from where you are getting that object, as per that we have to change the logic what i have mentioned above is simple common logic to update object value.
You can delete the params data as below:
useFocusEffect(useCallback(() => {
if (route.params) {
const keys = Object.keys(route.params)
if (keys && keys.length > 0) {
const removeableKey = keys[0]
delete route.params[removeableKey] // save data before deleting the params
}
}
}, [route.params]))

typescript how to find inside an array that is already in an array?

I want to find a value inside an array that is already inside an array.
To give an example of my array:
[
{
ConcessionId: 1,
ConcessionName: "Coyotes",
KnownAs: [
{
TeamId: 1,
Name: "Arizona Coyotes",
},
{
TeamId: 2,
Name: "Phoenix Coyotes",
}
]
},
{
ConcessionId: 2,
ConcessionName: "Devils",
KnownAs: [
{
TeamId: 3,
Name: "Colorado Rockies",
},
{
TeamId: 4,
Name: "New-Jersey Devils",
}
]
}
]
What I want is when Icall my function it returns me the team name.
For example, I the parameter value is 3, I want Colorado Rockies as a name:
public getInfo(_TeamID) {
const concession: ConcessionInfo[] = this.concessionList$.filter(function (x) {
x.KnownAs.filter( (y)=> {
y.TeamId= +_TeamID;
return y.Name;
})
})
}
I try so many different way with filter. But never get something good. Never works.
I can make a double .foreach , for each array. but I think a better method exist than making a double loop.
Thanks
Instead of using the filter method (which is in fact working similar as a for loop), you could do forEach on both arrays. For your current data structure, there is no other way around it.
getInfo = (_TeamID) => {
let teamName = '';
this.concessionList$.forEach(entry => {
entry.KnownAs.forEach(team => {
if(team.TeamId === _TeamID){
teamName = team.Name;
return; // break the loop.
}
})
});
return teamName;
}
Here is a working example
https://stackblitz.com/edit/double-for-lopp
EDIT
If you have a look at the polyfill implementation of filter from Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter which is in equivalent to the native implementation of filter, you can see that it is looping through the whole array, the same way as a forEach loop. The difference is that the filter method will return a new array based on the boolean condition inside the callback function, while a forEach loop does not return anything.
Assuming myArray is contains the data you provided.
The following code will work if you're using Typescript 3.7 and above.
public getInfo(teamId: number): string | undefined {
const team = this.concessionList$
.map(concession => concession.KnownAs)
.reduce((a, b) => a.concat(b), [])
.find(team => team.TeamId === teamId)
return team ? team.Name : undefined
}
Usage:
this.getInfo(3) // Colorado Rockies
Ok how this work?
You have to understand what is find. For example:
const result = [{name: 'foo', age: 1}, {name: 'bar', age: 2}]
.find(people => people.name === 'foo')
console.log(result) // {name: 'foo', age: 1}

React native identify a boolean within an object

I am trying to make an app(IOS and Android) for ads and I want to be able to go into the objects of my ads and identify a boolean and if it is true do one thing and something else otherwise.
Here are the objects of an ad:
I want to go into the object and if the "ReceiveHelp" is true i want the code to execute say blue as backgroundcoulor otherwise red. The problem is I don't know how to go into the object and identify the boolean props only.
export const publicAdFetch = () => {
return (dispatch) => {
firebase.database().ref('/users').once('value').then((snapshot) => {
const usersData = snapshot.val();
let sortedAdds = Object.keys(usersData).reduce((prev, userId) => {
let ads = usersData[userId].ads;
ads = Object.keys(ads).map(key => {
return { ...ads[key], id: key };
});
return prev.concat(ads);
}, [])
.sort((a, b) => (b.time - a.time));
this is the code I currently have to put everything into an array and then sort by time. But I have no idea how to just see if the boolean is true or false
You can check for a boolean with typeof
const yourObjArray = [
{desc: "fdf", price: "rrr", receiveHelp: true},
{desc: "ccc", price: "254", receiveHelp: 351},
{desc: "aaa", price: "gdg", receiveHelp: false},
{desc: "aaa", price: "gdg", receiveHelp: "charlie"},
{desc: "feee", price: "jth", receiveHelp: true},
];
yourObjArray.forEach(obj => console.log("The type is: ", typeof obj.receiveHelp));
Once you know if the receiveHelp is a boolean you can check for true or false easily with if():
const receiveHelp = true;
if (typeof receiveHelp === 'boolean') {
if (receiveHelp) { // This equals to if (receiveHelp === true)
console.log("this is true: ", receiveHelp);
} else { // else false
console.log("this is false: ", receiveHelp);
}
}
Thanks #Rodius
You're help gave me some inspiration!
I solved it but doing:
let iftrue = '#666';
if (this.props.callbackFromParent.receiveHelp) {
iftrue = '#ff0';
and then in my styles for the ad i had "iftrue", didn't realize it was so simple that ".receiveHelp" was enough to go into the object to check on the values.

How dynamically transform my "Object" to List in ng-model at view

I'm trying to transform my object to list dynamically, so I'm building at view instead of declaring at controller.
I don't want to declare like this: custom_fields.title_field.type_text_field = [] because the title_field is built dynamic, it could be any kind of text like full_name
My json as is:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":{
"name":"John",
"first_name":"Wick"
},
"type_boolean_field":{
"is_badass": true,
"is_good_movie": true
},
"type_select_field": {
"this_select": 1,
"i_got_this": "nope i didnt got this"
}
},
And to be:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":[{
"name":"John",
"first_name":"Wick"
}],
"type_boolean_field":[{
"is_badass": true,
"is_good_movie": true
}],
"type_select_field": [{
"this_select": 1,
"i_got_this": "nope i didnt got this"
}]
},
the object I'm trying to transform into array is type_text_field which can be dynamic too, like type_date_field or type_select_field and so on.
My ng-model is like this:
ng-model="objectApp.application.applicant.custom_fields[layout.dynamic_title][input.type][input.variable]"
the [input.type] is that I'm trying to transform into array, how can I achieve this? I tried to use $index, but got strange results.
We can do it by 2 solutions:
There is a question about your task:
? how you want handle if we have more than one type_text_field in title_dynamic_generate_field? because you want to convert it to "type_text_field":[{},...]
however my answers about the question are:
If we know what's the dynamic params which we want to send theme as json, i mean if we know what is the key of title_dynamic_generate_field or type_text_field, we do as this sample:
var data = {
"custom_fields": {
dynamicParamIs1: 'title_dynamic_generate_field',
dynamicParamIs2: 'type_text_field',
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var paramHelper1 = json.custom_fields[json.custom_fields.dynamicParamIs1];
var paramHelper2 = json.custom_fields.dynamicParamIs2;
var solutionA = function (object, as) {
var array = [];
for (var key in object) {
var newObject = object[key];
array.push(newObject);
}
object[as] = array;
}
solutionA(paramHelper1, paramHelper2);
We changed a model of our json which can help us to detect (find) the keys
If we don't know what is the dynamic params are, we do as this:
var data = {
"custom_fields": {
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var solutionB = function (json) {
var array = [];
for (var key in json) {
var j1 = json[key];
for (var key2 in j1) {
var j2 = j1[key2];
for (var key3 in j2) {
var fullObject = j2[key3];
array.push(fullObject);
j2[key3] = array;
}
}
}
}
solutionB(data);
This sample is manual which we use nested for to detect the keys name

Resources