Check if a string contains another string React Native - javascript

I am trying to filter an array of data like so:
let data =
[
{
"approval": "TPED",
"manufacturer": "Chesterfield"
},
{
"approval": "BV",
"manufacturer": "Faber"
}
]
let approvalVariable = "TP"
let filteredData = data.filter(x => x.approval.includes(approvalVariable))
console.log(filteredData)
So if approvalVariable is "TP", I want the new array to be:
[
{
"approval": "TPED",
"manufacturer": "Chesterfield"
},
]
I have it working when I do:
let filteredData = data.filter(x => x.approval == approvalVariable)
But when I try:
x.approval.includes(approvalVariable)
I get an error that x.approval.includes is not an object
I had it working at one point with .includes() but something is going wrong now.
Any help would be greatly appreciated.
componentWillMount() {
this.fetchData();
}
fetchData = async () => {
var fireBaseResponse = firebase.database().ref();
fireBaseResponse.once('value').then(snapshot => {
let data1 = [];
let approval = this.props.navigation.state.params.approval
let comments = this.props.navigation.state.params.comments
let designStandard = this.props.navigation.state.params.designStandard
let diameter = this.props.navigation.state.params.diameter
let h2Compatible = this.props.navigation.state.params.h2compatible
let inletThread = this.props.navigation.state.params.inletThread
let manufacturer = this.props.navigation.state.params.manufacturer
let specificationNumber = this.props.navigation.state.params.specificationNumber
let testPressure = this.props.navigation.state.params.testPressure
let waterCapacity = this.props.navigation.state.params.waterCapacity
let workingPressure = this.props.navigation.state.params.workingPressure
snapshot.forEach(item =>{
const temp = item.val();
data1.push(temp);
return false;
});
////////Filter Method/////////
if(approval == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.approval.includes(approval))
}
if(waterCapacity == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.waterCapacity == waterCapacity)
}
if(designStandard== '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.designStandard == designStandard)
}
if(diameter == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.diameter == diameter)
}
if(inletThread == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.inletThread == inletThread)
}
if(workingPressure == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.workingPressure == workingPressure)
}
if(comments == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.comments == comments)
}
if(manufacturer == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.manufacturer == manufacturer)
}
if(testPressure == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.testPressure == testPressure)
}
if(specificationNumber == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.specificationNumber == specificationNumber)
}
if(h2Compatible == '') {
console.log("good")
}
else {
data1 = data1.filter(x => x.h2Compatible == h2Compatible)
}
/////////////////////Filter Method//////////////////
this.setState({data: data1});
});
}
render(){
var {navigate} = this.props.navigation;
let {params} = this.props.navigation.state;
return(
<ViewContainer>
<ScrollView>
<FlatList
data = {this.state.data}
keyExtractor = {(x, i) => i}
renderItem ={({item}) =>
<Text style = {styles.itemText}>
Approval: {item.approval} | Manufacturer: {item.manufacturer} | Specification Number: {item.specificationNumber} |
H2 Compatible: {item.h2Compatible} | Diameter: {item.diameter} | Water Capacity: {item.waterCapacity} |
Inlet Thread: {item.inletThread}{"\n"}
</Text>
}
/>
</ScrollView>
<View style ={styles.footer}>
<TouchableOpacity style ={styles.footerButton} onPress = { () => navigate("ValveSearchScreen")}>
<Text style ={styles.footerButtonText}>SEARCH</Text>
</TouchableOpacity>
</View>
</ViewContainer>
)
}
}

The problem was that it was searching for a property within the array object called includes. Obviously it could not find it so it was giving me the warning that the property did not exist. To fix this I changed the line to
let filteredData = data.filter(x => String(x.approval).includes(approvalVariable));
I hope this helps somebody else out in the future and you don't spend a week trying the figure it out with no help like I did.

Related

How to push object into array angular 8

i am getting below example data in this.selectedParameterContext.
Please try the below code.
deleteAllContextData(data) {
const newSelectedParameterContext = {
'records': []
};
this.selectedParameterContext.records.forEach(function (record) {
const newSelectedParameterValues = [];
record.values.forEach(function (parameter, parameterIndex) {
const isValid = data.data.values.find(function (item) {
return parameter.value === item.value && parameter.label === item.label;
});
if (isValid) {
newSelectedParameterValues.push(parameter);
}
});
newSelectedParameterContext.records.push({ ...record, 'values': newSelectedParameterValues });
});
this.selectedParameterContext = newSelectedParameterContext;
}

Console.log(myState) shows full array, but Console.log(myState.length) gives 0

I am a beginner in React working on a Attendance-System Project.(Sorry for all the bad code)
So I have this component called ShowData, and it receives some props from it's parent component. I am using conditional rendering in this. So I have only one state variable called filteredUsers, and it's initialized to an empty array.
Now what I want to do is fetch all the User Data from firebase and once I have all the users, I set my state equal to that. So for that I have a useEffect()
which has this async function called init()
Now the problem is that, when I try to use filteredUsers.length in the conditional rendering part, it gives me 0.
import React from "react";
import { db } from "./firebase";
import { dateStripper, getDaysArray } from "./utils";
import "./ShowData.css";
import MusterUser from "./MusterUser";
function ShowData(props) {
let { userid, date, format, employee } = props;
let [filteredUsers, setFilteredUsers] = React.useState([]);
console.log(date);
React.useEffect(() => {
console.log("UseEffect triggered");
async function getUserData(employeeID, currentDate) {
let attendanceDoc = await db
.collection(userid)
.doc("Att-Records")
.collection(currentDate)
.doc(employeeID)
.get()
.then((doc) => {
if (!doc.exists) {
return { data: null, currentDate: currentDate };
}
return { data: doc.data(), currentDate: currentDate };
});
return attendanceDoc;
}
async function getEmployees() {
return await db
.collection(userid)
.doc("Employee-Records")
.collection("UUID-Data")
.get()
.then((employeeSnapshot) => {
let temp = [];
employeeSnapshot.forEach((employeeDoc) => {
temp.push(employeeDoc);
});
return temp;
});
}
async function init() {
let allDates = [];
let musterUsers = [];
let dates = getDaysArray(date[0], date[1]);
if (date[0] === date[1]) {
dates.pop();
}
dates.forEach((date) => {
allDates.push(dateStripper(date));
});
if (format === "muster" && employee === "all") {
let serialNum = 0;
let users = await getEmployees();
users.forEach(async (user) => {
serialNum = serialNum + 1;
let tempUser = {
SNo: serialNum,
name: user.data()["Employee Name"],
dept: user.data()["Employee Department"],
desg: user.data()["Employee Designation"],
total: 0,
present: 0,
absent: 0,
miss: 0,
};
let calls = [];
allDates.forEach(async (date) => {
calls.push(getUserData(user.id, date));
});
let userPerDates = await Promise.all(calls);
userPerDates.forEach((callbackResult) => {
let data = callbackResult.data;
let currentDate = callbackResult.currentDate;
if (data) {
tempUser["total"] = tempUser["total"] + 1;
if (data["Status"] === "A") {
tempUser[currentDate] = "Absent";
tempUser["absent"] = tempUser["absent"] + 1;
} else if (data["Status"] === "P") {
tempUser[currentDate] = "Present";
tempUser["present"] = tempUser["present"] + 1;
} else if (data["Status"] === "MIS") {
tempUser[currentDate] = "MIS";
tempUser["miss"] = tempUser["miss"] + 1;
}
} else {
tempUser[currentDate] = "N/A";
}
});
musterUsers.push(tempUser);
});
return musterUsers;
}
}
if (date.length) {
console.log("init triggered");
init().then((musterUsers) => {
setFilteredUsers(musterUsers);
});
} else {
console.log("not triggered");
}
}, [date, format, employee]);
if (!date.length) {
console.log("NoDate");
return (
<div className="noData">
<h1>Nothing to show</h1>
</div>
);
} else {
console.log(filteredUsers);
console.log(format);
let allDates = [];
let dates = getDaysArray(date[0], date[1]);
if (date[0] === date[1]) {
dates.pop();
}
dates.forEach((date) => {
allDates.push(dateStripper(date));
});
console.log("I reached here");
console.log(filteredUsers.length);
if (format === "muster" && filteredUsers.length > 0) {
console.log("Main function runs");
return (
<div className="data">
<div className="data__header">
<h1>Muster Roll</h1>
<h1>
From {allDates[0]} to {allDates[allDates.length - 1]}
</h1>
</div>
<div className="data__box">
<div className="data__columns">
<li>Employee Name</li>
<li>Employee Department</li>
<li>Employee Designation</li>
{allDates.map((allDates) => (
<li className="dateColumn">{allDates}</li>
))}
<li>Total</li>
<li>Present</li>
<li>Absent</li>
<li>Miss</li>
</div>
<div className="muster__users">
<MusterUser user={filteredUsers} />
</div>
</div>
</div>
);
} else {
return <h1>OOPS</h1>;
}
}
}
export default ShowData;
Refer to the Using the State Hook
const [myState, setMyState] = React.useState([]);
...
newArray = ["Hello", "World", "Know"]
setMyState(newArray)
...
React.useEffect(() => {
console.log(myState)
}, [ myState ])
...
return
(<div>
{!date.length ?
<div className="noData">
<h1>Nothing to show</h1>
</div> :
<div>
....
</div>
}
</div>)
instead of pushing elements one by one to the array, just use a temporary array and update it any number of times you want and then finally make your state equal to that array.

Alert Controller stacked in nested condition

I am doing a comparison to validate QR Code using the data retrieved from Firestore. It should navigate to another page if the condition is satisfied. Based on my code, it kept on returning 'Invalid Code' and multiple stacked alerts even if the condition is true. Is there a simpler solution to compare? I just can't quite figure it out. Here's my code.
scan() {
this.scanner.scan().then((data) => {
let qrcode = data.text.length;
this.afs.firestore.collection('item1')
.get()
.then((snapshot) => {
snapshot.docs.forEach(doc1 => {
var data1 = doc1.data();
var itemName = data1.itemname;
var itemID = data1.itemid;
this.afs.firestore.collection('item2')
.get()
.then((snapshot) => {
snapshot.docs.forEach(doc2 => {
var data2 = doc2.data();
var itemName2 = data2.itemname2;
var itemID2 = data2.itemid2;
var description = data2.description;
if (doc1.exists) {
if (qrcode == 10 && itemName == itemName2 && itemID == itemID2) {
this.navCtrl.navigateForward('/nextPage');
} else {
return this.presentAlert('Error', 'Invalid Code')
}
} else if (description == null) {
return this.presentAlert('Error', 'Nothing found')
} else {
return this.presentAlert('Error', 'QR Not Found')
}
})
})
})
})
}, (err) => {
console.log('Error: ', err);
})
}
I think that your issue is because you have 2 nested "forEach" cycles and even is you routine has a valid condition there isn't a return statement and your cycles never been stopped(using break)
I adjusted your code to break the cycles
scan() {
this.scanner.scan().then((data) => {
let qrcode = data.text.length;
this.afs.firestore.collection('item1')
.get()
.then((snapshot) => {
snapshot.docs.forEach(doc1 => {
var data1 = doc1.data();
var itemName = data1.itemname;
var itemID = data1.itemid;
var check = this.afs.firestore.collection('item2')
. get()
.then((snapshot) => {
snapshot.docs.forEach(doc2 => {
var data2 = doc2.data();
var itemName2 = data2.itemname2;
var itemID2 = data2.itemid2;
var description = data2.description;
if (doc1.exists) {
if (qrcode == 10 && itemName == itemName2 && itemID == itemID2) {
return true
} else {
return this.presentAlert('Error', 'Invalid Code')
}
} else if (description == null) {
return this.presentAlert('Error', 'Nothing found')
} else {
return this.presentAlert('Error', 'QR Not Found')
}
})
})
if (check){
this.navCtrl.navigateForward('/nextPage');
break
}else{
return check
}
})
})
}, (err) => {
console.log('Error: ', err);
})
}

Linear flow of multiple intent is not working

I am working on a project of Amazon Alexa of booking a table in a restaurant and I have four intents:
makeReservation
futureOrCurrentLocation
getRestaurantName
selectRestaurants
I am facing one issue that the linear flow of intent is not working. I have stored the previous intent in the session and checked the previous intent from the session and on that basic I am calling the next intent.
But when I say Alexa with the previous intent String in the response of the current intent, it jumps to the new intent we have called, but it throws an exception.
Actually it should work like if I say some intent String in the response of other intent then it should repeat the current intent once again.
And one more issue I am facing is that I need to append the String in the user utterance like e.g.:
Alexa: "Where would you like to go?"
User: "Go to {Restaurant Name}"
I didn't want to append this "Go to" in the restaurant name.
// Lambda Function code for Alexa.
const Alexa = require("ask-sdk");
// Book a table
const makeReservation_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'makeReservation' ;
},
handle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
sessionAttributes.tableTalkType = 1;
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
return responseBuilder
.addDelegateDirective({
name: 'futureOrCurrentLocation',
confirmationStatus: 'NONE',
slots: {}
})
.withShouldEndSession(false)
.getResponse();
},
};
const futureOrCurrentLocation_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'futureOrCurrentLocation' ;
},
async handle(handlerInput) {
const { requestEnvelope, serviceClientFactory, responseBuilder } = handlerInput;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'makeReservation') {
const request = handlerInput.requestEnvelope.request;
// const responseBuilder = handlerInput.responseBuilder;
const slotValues = getSlotValues(request.intent.slots);
const location = slotValues.locationType.heardAs;
const tableTalkType = sessionAttributes.tableTalkType;
let say = '';
// delegate to Alexa to collect all the required slots
const currentIntent = request.intent;
if (request.dialogState && request.dialogState !== 'COMPLETED') {
return handlerInput.responseBuilder
.addDelegateDirective(currentIntent)
.getResponse();
}
if (location == 'future location') {
say = `Future location not available at this moment. Please ask to current location.`;
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
} else if(location == 'current location' && tableTalkType == 1){
return responseBuilder
.addDelegateDirective({
name: 'getRestaurantName',
confirmationStatus: 'NONE',
slots: {}
})
.getResponse();
} else if (location == 'current location' && tableTalkType == 2) {
return userCreatedTableListing_Handler.handle(handlerInput);
} else {
say = `invalid input.Please try again`;
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
},
};
const getRestaurantName_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'getRestaurantName' ;
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'futureOrCurrentLocation') {
const request = handlerInput.requestEnvelope.request;
let slotValues = getSlotValues(request.intent.slots);
// delegate to Alexa to collect all the required slots
const currentIntent = request.intent;
if (request.dialogState && request.dialogState !== 'COMPLETED') {
return handlerInput.responseBuilder
.addDelegateDirective(currentIntent)
.getResponse();
}
// SLOT: restaurantname
if (request.dialogState && request.dialogState == 'COMPLETED' && slotValues.restaurantname.heardAs) {
return new Promise((resolve) => {
getRestaurants(slotValues, handlerInput).then(say => {
resolve(handlerInput.responseBuilder.speak(say).reprompt(say).withShouldEndSession(false).getResponse());
}).catch(error => {
console.log(error);
});
});
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
}
};
const selectRestaurants_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'selectRestaurants' ;
},
handle(handlerInput) {
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let previousIntentName = getPreviousIntent(sessionAttributes);
if (previousIntentName == 'getRestaurantName') {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let slotValues = getSlotValues(request.intent.slots);
let say = '';
let restaurantListArray = sessionAttributes.sessionrestaurantList ? sessionAttributes.sessionrestaurantList : [];
sessionAttributes.previousIntent = '';
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
let restaurantIndex = slotValues.selectRestaurant.heardAs;
let restaurantData = {
name: '',
address: '',
restaurantlatitude: '',
restaurantlongitude: '',
restaurantID:'',
restaurantImageUrl: '',
date: '',
time:'',
people: '',
};
if (restaurantListArray.length >= restaurantIndex) {
let jsonData = JSON.parse(restaurantListArray[restaurantIndex - 1]);
if ((restaurantIndex) && (jsonData[restaurantIndex].name !== '' && typeof jsonData[restaurantIndex].name !== undefined && jsonData[restaurantIndex].name !== null)) {
let restaurantAddress1 = jsonData[restaurantIndex].location.address1 ? jsonData[restaurantIndex].location.address1: '';
let restaurantAddress2 = jsonData[restaurantIndex].location.address2 ? jsonData[restaurantIndex].location.address2: '';
let restaurantAddress3 = jsonData[restaurantIndex].location.address3 ? jsonData[restaurantIndex].location.address3: '';
restaurantData['name'] = jsonData[restaurantIndex].name;
restaurantData['address'] = restaurantAddress1.concat(restaurantAddress2, restaurantAddress3);
restaurantData['restaurantID'] = jsonData[restaurantIndex].id;
restaurantData['restaurantImageUrl'] = jsonData[restaurantIndex].image_url;
restaurantData['restaurantlatitude'] = jsonData[restaurantIndex].coordinates.latitude;
restaurantData['restaurantlongitude'] = jsonData[restaurantIndex].coordinates.longitude;
sessionAttributes.restaurantData = restaurantData;
handlerInput.attributesManager.setSessionAttributes(sessionAttributes);
say = `selected Restaurant name is ${jsonData[restaurantIndex].name} in ${restaurantAddress1} ${restaurantAddress2} ${restaurantAddress3}.`;
return responseBuilder
.addDelegateDirective({
name: 'bookingDate',
confirmationStatus: 'NONE',
slots: {}
})
.speak(say)
// .reprompt('try again, Please provide date')
.withShouldEndSession(false)
.getResponse();
} else {
say = 'Restaurant not available. please say again';
return responseBuilder
.speak(say)
.reprompt('Restaurant not available. please say again')
.withShouldEndSession(false)
.getResponse();
}
} else {
say = 'Please select valid input.';
return responseBuilder
.speak(say)
.reprompt('Please select valid input')
.withShouldEndSession(false)
.getResponse();
}
} else {
return errorIntent_Handler.handle(handlerInput);
}
},
};
const errorIntent_Handler = {
canHandle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
return request.type === 'IntentRequest' && request.intent.name === 'errorIntent' ;
},
handle(handlerInput) {
const request = handlerInput.requestEnvelope.request;
const responseBuilder = handlerInput.responseBuilder;
let sessionAttributes = handlerInput.attributesManager.getSessionAttributes();
let say = 'Sorry. There is some problem with the response. Please say again';
return responseBuilder
.speak(say)
.reprompt(say)
.getResponse();
},
};

Searching For Nested Object in Angular

I have a problem searching for a nested array in my Angular app. I have to access the package.name. Please help thanksenfoiewfhfofhfowfoewhfowfoewhfwefwfhowefweofhew8ofwofhewofw8eofhwf
JSON
[{
"id": 1,
"name": "Yeah",
"package_id": 1,
"price": 100,
"package": {
"id": 1,
"name": "Yeah"
}
}]
TS
search(event) {
const val = event.target.value.toLowerCase();
if (!val) {
this.users = this.tempUsers;
}
const temp = this.tempUsers.filter((row) => {
return Object.keys(row).some((property) => {
return row[property] === null ? null : row[property].toString().toLowerCase().indexOf(val) !== -1;
});
});
this.users = temp;
}
TS
getAllUsers() {
this.usersService.getAll()
.subscribe(
(data: any) => {
console.log(data);
this.users = data.Users;
this.tempUsers= [...this.users];
},
error => {
console.log(error);
});
}
Does this work for you,
const temp = this.tempUsers.filter((row) => {
return Object.keys(row).some((property) => {
if (property === 'package') {
// check package.name value here
// like return row[property].name === 'something' ? true : false;
} else {
// the rest of the outer properties can be checked here
// not modifying your code here, but make sure it works for you
return row[property] === null ? null : row[property].toString().toLowerCase().indexOf(val) !== -1;
}
});
});
I have only answered your question on how to access the nested object inside the array method. Hope it helps or gives you an idea to fine tune your solution.
According to your data, You can use the following filter;
const filteredData = data.filter((item) => item.price.toString() === val || item.package_id.toString() === val || item.package.name.toString().toLowerCase().indexOf(val) !== -1 );
// UPDATED WITH CODE
search(event) {
const val = event.target.value.toLowerCase();
const filteredData = this.users.filter((item) => item.price.toString() === val ||
item.package_id.toString() === val ||
item.package.name.toString().toLowerCase().indexOf(val) !== -1 );
this.users = filteredData ;
}

Categories

Resources