how i can get a value through key - javascript

i want to know how i can get a value/numbers through key/username ?
look like that console.log(acc.${username})
my js
...
app.get("/account", (req, res) => {
loggedIn = req.cookies.loggedIn;
username = req.cookies.username;
if (loggedIn == "true") {
db.list().then(keys => {
if (keys.includes(username)) {
res.render("settings.html", { username: username })
var data = fs.readFileSync('2FA.json');
var acc = JSON.parse(data)
//////////////////////////////////////////////
console.log(acc.${username}) // i want to see a numbers in user name look like in here
/////////////////////////////////////////////
} else {
res.redirect("/logout");
}
});
} else {
res.render("notloggedin.html");
}
});
my json
[
{
"youssefnageeb": 927342
},
{
"youssefnageeb1":310686
},
{
"youssefnageeb2": 105380
},
{
"youssefnageeb3": 431816
},
{
"youssefnageeb4": 484728
}
]

I am guessing "data" is in the format mentioned above.
So, you can do
const index = data.findIndex(function isAccountRow(row) { return typeof row[username] === 'number'; })
if(index === -1) {
return res.redirect("/logout");
}
const row = data[index];
console.log(row[username]); // will be the number

Related

how to loop through and remove the object in which array is empty

FilterCriterias: any = []
public productChanged(filterValue: any) {
if(this.FilterCriterias?.length == 0) {
this.FilterCriterias.push({
filtercolumnName: 'productType',
filterValueList: [filterValue.name]
})
} else {
this.FilterCriterias.forEach((elem: any, index: number) => {
if(elem.filtercolumnName == 'productType') {
const idx = elem.filterValueList.indexOf(filterValue.name)
if(idx >= 0) {
elem.filterValueList.splice(idx, 1)
// if (elem.filterValueList?.length == 0 && elem.filtercolumnName == 'productType') {
// const idy = elem.filtercolumnName.indexOf('productType')
// if (idy > 0) {
// this.FilterCriterias.splice(idy, 1)
// }
// }
} else {
elem.filterValueList.push(filterValue.name)
}
} else {
this.FilterCriterias.push({
filtercolumnName: 'productType',
filterValueList: [filterValue.name]
})
}
});
}
this.FilterCriterias.forEach((element: any) => {
if(element.filterValueList.length == 0 && element.filtercolumnName == 'productType') {
console.log(true);
const idy = element.filtercolumnName.indexOf('productType')
console.log(idy);
}
});
// removing the duplicates
var filtered = this.FilterCriterias.reduce((filtered: any, item: any) => {
// console.log(item);
if(!filtered.some((filteredItem: any) => JSON.stringify(filteredItem.filtercolumnName) == JSON.stringify(item.filtercolumnName)))
filtered.push(item)
return filtered
}, [])
console.log('filtered',filtered);
}
public collectionChanged(filterValue: any) {
if(this.FilterCriterias?.length == 0) {
this.FilterCriterias.push({
filtercolumnName: 'collections',
filterValueList: [filterValue.name]
})
} else {
this.FilterCriterias.forEach((elem: any, index: number) => {
if(elem.filtercolumnName == 'collections') {
const idx = elem.filterValueList.indexOf(filterValue.name)
if(idx >= 0) {
elem.filterValueList.splice(idx, 1)
// if(elem.filterValueList?.length == 0) {
// const idy = elem.filtercolumnName.indexOf('collections')
// console.log('collectoinindex',idy);
// if(idy > 0) {
// this.FilterCriterias.splice(idy, 1)
// }
// }
} else {
elem.filterValueList.push(filterValue.name)
}
} else {
this.FilterCriterias.push({
filtercolumnName: 'collections',
filterValueList: [filterValue.name]
})
}
});
}
this.FilterCriterias.forEach((element: any) => {
if(element.filterValueList.length == 0 && element.filtercolumnName == 'collections') {
console.log(true);
const idy = element.filtercolumnName.indexOf('collections')
console.log(idy);
}
});
// removing the duplicates
var filtered = this.FilterCriterias.reduce((filtered: any, item: any) => {
// console.log(item);
if(!filtered.some((filteredItem: any) => JSON.stringify(filteredItem.filtercolumnName) == JSON.stringify(item.filtercolumnName)))
filtered.push(item)
return filtered
}, [])
console.log('filtered',filtered);
}
I am having two functions in which I want to generate a format like below
FilterCriterias: [
{
filtercolumnName:`producttype`,
filterValueList: [`hat`, 'cup']
},
{
filtercolumnName: "collections",
filterValueList: [`modern`, 'pant']
},
]
if the filterValueList.length == 0 means i want to remove the entire object which hold the filerValueList.length == 0.
For Example, if filterValueList of collections is empty means only the producttype needs to be there in the array.
You can achieve that using Array.filter function, like the following:
this.FilterCriterias = this.FilterCriterias.filter(
(item) => !!item.filterValueList.length
);
I am guessing this should do the job if I understood correctly what you want to do. This will loop through all objects of the array, check if their filterValueList array is empty and if so, it will remove them from the array:
let i = 0;
while (i < FilterCriterias.length) {
if(FilterCriterias[i].filterValueList.length == 0) {
FilterCriterias.splice(i, 1);
} else {
i++;
}
}

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;
}

Run function if other end Vue, JS

I'm don't know how to run code if other end
Function showAvailableTable refresh item and add data to vuex $store
I need to run code from ////START to //// END if showAvailableTable() done correctly(axios add data to $store)
how should I do it correctly?
showAvailableTable () {
var obj = this.firstStepData
var nullCount = 0
var self = this
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key] == null) {
nullCount++
}
}
if (nullCount === 0) {
var reservationId = this.firstStepData.restaurant.id
var restaurantSize = this.firstStepData.tableSize.value
var reservationDate = this.firstStepData.reservationDate
var reservationTime = this.firstStepData.reservationTime
axios
.get(self.$store.state.apiUrl + 'reservation/tables/?size=' + restaurantSize + '&restaurant_id=' + reservationId + '&date=' + reservationDate + '&hour=' + reservationTime)
.then(response => {
this.$store.commit('updateRestaurantTableList', response.data)
})
.catch(error => {
console.log(error)
})
this.$store.commit('updateShowTable', true)
}
},
Next function, this function booking table, I'm run this.showAvailableTable() to refresh data in $store
firstStepBook (event, id) {
this.showAvailableTable()
///////////////////START
var isResData = false
this.dataLoading = true
for (var obj in this.restaurantTableList) {
if (this.restaurantTableList[obj].id === id) {
if (this.restaurantTableList[obj].res_tab.length > 0) {
isResData = true
}
break
}
}
if (isResData && !event.currentTarget.classList.contains('isSelected')) {
alert('someone is booking this table, choose another one')
} else {
if (event.currentTarget.classList.contains('isSelected')) {
this.deleteTmpReservation(this.reservationTmp.id)
this.dataLoading = false
} else {
if (this.reservationTmp.id !== undefined) {
this.deleteTmpReservation(this.reservationTmp.id)
this.dataLoading = false
}
var self = this
axios.post(self.$store.state.apiUrl + 'reservation/', {
restaurant_table: id,
clients_number: self.firstStepData.tableSize.value,
reservation_time: self.firstStepData.reservationTime,
reservation_date: self.firstStepData.reservationDate
})
.then(function (response) {
self.showAvailableTable()
self.$store.commit('updateReservationTmp', response.data)
self.dataLoading = false
})
.catch(function (error) {
console.log(error)
})
//this.$store.commit('updateStep', 2)
}
}///////////////////END
},
thank you in advance
This might suit you if the mutation is only called within showAvailableTable()
Ref Vuex subscribe
mounted() {
this.$store.subscribe((mutation, state) => {
if (mutation.type === 'updateRestaurantTableList') {
///////////////////START
...
///////////////////END
}
})
},
methods: {
firstStepBook (event, id) {
// call to updateRestaurantTableList triggers above subscription
this.showAvailableTable()
}
}

Vue test utils: TypeError mounted

I am having an issue with Vue Test Utils. When I run a unit test, I am always confronted with:
TypeError{line: 73983, sourceURL: 'http://localhost:9876/base/index.js?045b00affe888fcd6b346c4fe50eadd13d471383', stack: 'mounted#http://localhost:9876/base/index.js?045b00affe888fcd6b346c4fe50eadd13d471383:73983:30.....
This only happens when I have the mounted() function in the Vue component
Settings.vue
mounted() {
this.$refs.address.update(this.profile.address)
},
Settings.spec.js
it('calls updateUserInformation before mount', () => {
const spy = sinon.spy(Settings.methods, 'updateUserInformation')
shallow(Settings, { propsData })
Vue.nextTick().then(() => {
spy.should.have.calledOnce()
})
})
I am using Mocha & Chai with vue-test-utils. Does anyone know why this is happening?
Thank you in advance!
UPDATE
Settings.vue component HTML
<vue-google-autocomplete
ref="address"
id="map"
classname="input"
placeholder="Address"
v-on:placechanged="getAddressPlaceChanged"
v-on:inputChange="getAddressInputChange"
:country="['sg']"
>
</vue-google-autocomplete>
Settings.vue component Javascript
export default {
components: {
GoogleMaps,
AutoComplete,
VueGoogleAutocomplete,
Partner,
},
watch: {
// whenever school changes, this function will run
school() {
// Check if school value is an empty string or character is lesser than FIX_STR_LENGTH
if (this.school === '' || this.school.length < this.FIX_STR_LENGTH) {
this.removeMarker('school')
}
this.fetchSchools()
},
},
methods: {
async onSubmit() {
// Check if input fields are empty
if (this.address !== undefined && this.phoneNumber !== null && this.school !== '') {
const { placeResultData = {}, addressData = {} } = this.address
let isSuccessful = false
let tempLat = null
let tempLong = null
let tempAddress = null
// Check if address is an empty object
if (_.isEmpty(this.address)) {
const { latlong = {}, address = '' } = this.profile
const [lat, long] = latlong.coordinates
tempLat = lat
tempLong = long
tempAddress = address
} else {
// User changed address location
tempLat = addressData.latitude
tempLong = addressData.longitude
tempAddress = placeResultData.formatted_address
}
// Validate school address array
let tempSchoolAddress = []
if (this.selectedSchool !== null) {
tempSchoolAddress.push(this.selectedSchool.postal_code)
} else {
tempSchoolAddress = this.profile.schoolAddress
}
// Construct user object for registration/update
const user = new User(
this.profile.name,
tempAddress,
tempLat,
tempLong,
tempSchoolAddress,
)
// If user does not exist in database, perform a POST API registration request
if (this.userExist === false) {
// Add user properties for user registration
user.phoneNumber = this.phoneNumber
await UserSession.register(user, localStorage.getItem('id_token')).then((response) => {
const { data = {} } = response
const profile = data.user
this.updateUserInformation(profile)
isSuccessful = true
this.profile = profile
}).catch((error) => {
console.log(error.response)
})
}
// Perform a PUT API update request
await UserSession.update(user, localStorage.getItem('id_token')).then((response) => {
const { data = {} } = response
const profile = data.user
this.updateUserInformation(profile)
isSuccessful = true
this.profile = profile
}).catch((error) => {
console.log(error.response)
})
if (isSuccessful) {
this.profileChanged()
this.hasChanged = true
}
}
},
profileChanged() {
this.$emit('profileChanged', this.profile)
},
addMarker(name, params) {
if (params === null || params === '') {
return
}
gMapSession.default(params).then((response) => {
const { location = {} } = response.data.results[0].geometry
// Remove existing marker before replacing it
this.removeMarker(name)
this.markers.push({
position: location,
name,
})
this.zoom = 11
}).catch((error) => {
console.log(error.response)
})
},
removeMarker(name) {
let index = 0
let exist = false
for (let i = 0; i < this.markers.length; i++) {
if (this.markers[i].name === name) {
index = i
exist = true
break
}
}
if (exist) {
this.markers.splice(index, 1)
}
},
// Function called when user selects an option from the school autocomplete dropdown
getSelectedSchoolData(event) {
this.selectedSchool = event
// Check if selected school is defined
if (this.selectedSchool !== undefined && this.selectedSchool !== null) {
this.addMarker('school', this.selectedSchool.postal_code)
} else {
this.removeMarker('school')
}
},
// Function called when user types in the address autocomplete input field
getAddressInputChange(data) {
const { newVal = {} } = data
if (newVal === '' || newVal.length < this.FIX_STR_LENGTH) {
this.removeMarker('user')
}
},
// Function called when user selects an option from the address autocomplete dropdown
getAddressPlaceChanged(addressData, placeResultData) {
this.address = {
placeResultData,
addressData,
}
if (addressData !== undefined && addressData !== null) {
this.addMarker('user', addressData.postal_code)
} else {
this.removeMarker('user')
}
},
async updateUserInformation(profile) {
this.phoneNumber = profile.phoneNumber
this.addMarker('user', profile.address)
// TODO: schoolAddress is an array and UI must cater to multiple schools
await SchoolSession.default(profile.schoolAddress[0]).then(async (res) => {
const { result = {} } = res.data
const { records = [] } = result
// Assume that a single postal code contains only 1 school
this.school = records[0].school_name
this.addMarker('school', records[0].postal_code)
})
},
// Fetch school information base on school search query
fetchSchools: _.debounce(function getSchools() {
if (this.school.trim() === '') {
this.schools = []
return
}
const vm = this
SchoolSession.default(this.school).then((response) => {
// JSON responses are automatically parsed.
const { records = {} } = response.data.result
vm.schools = records
}).catch((error) => {
console.log(error.response)
})
}, 500),
},
data() {
return {
FIX_STR_LENGTH: 5,
school: '',
address: '',
schools: [],
markers: [],
phoneNumber: null,
selectedSchool: null,
userExist: false,
hasChanged: false,
center: { lat: 1.3521, lng: 103.8198 },
zoom: 7,
}
},
async created() {
this.profile = this.$attrs
// Check if user was a registered member by phone number
if (this.profile.phoneNumber === undefined) {
return
}
// User exist in the database
this.userExist = !this.userExist
// Update form information
this.updateUserInformation(this.profile)
},
mounted() {
this.$refs.address.update(this.profile.address)
},
}

Firebase database how to list

I am trying to query a Firebase database. I have the following code, but it returns an empty list, when there is matching data.
loadData() {
this.firelist = this.af.database.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
}).map(items => {
const filtered = items.filter(item => {
item.memberId1 === this.me.uid;
});
return filtered;
});
// if me not in firelist then create new chat
if (this.me && this.me.uid) {
let chatFound: boolean = false;
console.log('this.firelist', this.firelist);
this.firelist.forEach(chatItems => {
console.log('chatItems', chatItems);
for (let i = 0; i < chatItems.length; i++) {
console.log('chatItems['+i+']', chatItems[i]);
let memberId1: string = chatItems[i].memberId1;
let memberId2: string = chatItems[i].memberId2;
if (memberId1 === this.me.uid || memberId2 === this.me.uid) {
chatFound = true;
break;
}
}
if (!chatFound) {
//this.createChat();
}
});
}
}
I think my problem is with the filter.
The following code creates a chat successfully:
createChat(img1: string, img2: string) {
this.af.database.list('/chat/').push({
memberId1: this.me.uid,
memberId2: this.you.uid,
img1: img1,
img2: img2,
displayName1: this.me.displayName,
displayName2: this.you.displayName,
lastMsg_text: 'todo',
timestamp: Date.now(),
negativtimestamp: -Date.now()
})
}
The following filter works:
this.firelist = this.af.database.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
}).map(items => {
const filtered = items.filter(
item => item.memberId1 === this.me.uid
);
return filtered;
});

Categories

Resources