Selecting specific field(child field?) from firebase in react Native - javascript

Here is my firebase:
"Locations" : {
"location01" : {
"image" :
"https://www.senecacollege.ca/content/dam/projects/seneca/homepage-assets/homepage_intl.jpg",
"instructorName" : " OSMAN H.",
"place" : "Seneca, Scarborough",
"timing" : "TBA"
},
"location02" : {
"image" : "https://media-exp1.licdn.com/dms/image/C561BAQHrVTRjljcYnw/company-background_10000/0?e=2159024400&v=beta&t=fp0LWqyEnnXvxjzzdfuCHhX2jflJyhAkS0lMLXsPFw0",
"instructorName" : "AIYAZ NOOR",
"place" : "UTSC, Scarborough",
"timing" : "4 PM - 6 PM"
}
},
I know that if I get the data like this, then I can select/filter the specific field I want.
let locationsRef = db.ref('/Locations');
locationsRef.once('value', snapshot => {
let data = snapshot.val()
let locationsList = Object.values(data)
console.log(locationsList);
})
This unfortunately will give all the data as an array and displays each object. If the /locations branch had many records, it would take up space and in my opinion not best practice. Is there any way to select the 'place' field ONLY. The keys 'location01' and 'location02' can be anything. So I can't do something like (location/location01), this would take me into specific branch then. I want to get the 'place' field from all the branches.
I researched alot and had no luck. Any ideas/help are much appreciated!
Thank you in advance

I think what you are looking for is the .map function in JavaScript.
You can map over your locations object like this:
const locationsRef = db.ref('/Locations');
locationsRef.once('value', snapshot => {
let data = snapshot.val()
let locationsList = Object.values(data)
locationsList.map((location, index) => {
console.log(location.place);
// here you can do whatever you want with every single location object
// for example return a View that displays only the place
return <View><Text>{location.place}</Text></View>
});
});
You can read more about the .map function in the MDN docs here.
P.S.
I changed your use of let to const in case your DB data is a constant that you are not changing in this particular View.

Related

Searching Array of Objects with two search values

so I am trying to make an app that has two search criterias. The front-end app basically fetches data and you have two search bars to filter out the incoming data.
One search is by name and the other is by school name, the tricky part is that the either of the search also takes into account if there is some value in the other search parameter.
For example, if you search for "California University" and "Bob", you should get only Bobs that go to California University to render on the screen. But it seems like right now my DOM only renders the most recent search Ive made. What is the best way to go about a filter that filters both student name and school name using an event listener (keyup) on the search inputs?
searchByNameInput.addEventListener("keyup", (e) => {
const filterNameArray = studentArray.filter((student) => {
// code here to filter students with this name and render it on DOM
}
}
searchBySchoolName.addEventListener("keyup", (e) => {
//filters students who go to this school and render it on DOM
}
}
Write a single filtering function that checks both inputs, and call it from both event listeners.
function filterStudents() {
const nameFilter = searchByNameInput.value;
const schoolFilter = searchBySchoolName.value;
const filterArray = studentArray.filter(student =>
(nameFilter == '' || student.name.includes(nameFilter) &&
(schoolFilter == '' || student.school.includes(schoolFilter))
}
searchByNameInput.addEventListener("keyup", filterStudents);
searchBySchoolNameInput.addEventListener("keyup", filterStudents);
first filter your object and please try it include() method instead of filter().
as a above example
here filterData is my new filtered object and stu_data is my array.
get all search value from search input.
Example:-
var filterData = stu_data.filter((stu_filter) => {
return (stu_filter.firstname.toLowerCase().includes(filter) ||
stu_filter.lastname.toLowerCase().includes(filter))})
I hope this is help for you!
happy coding :)

Accessing the first value of the first key in an object

I am having a little bit of an issue trying to get the value of a certain object. Since this is a bit hard to explain, I'll set up a scenario that follows what I need.
{"Gmail": {"example#example.com": "password1", "anotherexample#example.com": "password2}, ...}
I have an object (as represented above, we will call the object "encrypted"). I can get the value "Gmail" by using Object.keys(encrypted)[i] where i represents the index I'm looking for. The issue I am encountering is, how do I get exaxmple#example.com or password1?
I've been aimlessly wandering around it for a while trying to figure this out, searching for answers, but I can't seem to do so or find any that aren't based on arrays. Any help is great, thank you!
You could use Object.entries
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
This turns objects into arrays of key - value which you can traverse, an example would be something like:
const data = {
"Gmail": { "example#example.com": "password1", "anotherexample#example.com": "password2" },
"Gmail2": { "example#example.com": "password1", "anotherexample#example.com": "password2" },
};
Object.entries(data).forEach(([key, value]) => {
const emailProvider = key;
const emailList = Object.entries(value);
console.log({ mail: emailProvider });
emailList.forEach(([email, password]) => {
console.log({ email, password })
})
});

How can I display my element dynamically based on data's fields?

I have my data in below:
fakeData = [
{
"option_name" : 'optionA',
"display_line_num" : 1
},
{
"option_name" : 'optionB',
"display_line_num" : 2
},
{
"option_name" : 'optionC',
"display_line_num" : 2
},
{
"option_name" : 'optionD',
"display_line_num" : 3
},
{
"option_name" : 'optionE',
"display_line_num" : 4
},
{
"option_name" : 'optionF',
"display_line_num" : 4
}
];
and I am trying to make my html look like desired look
The display_line_num represent which row the element should be placed.
I am pretty lost on how to approach to this.
my try here
I tried to create a hashmap where key is the line number, and value is how many options are in that line number. However, I am still lost.
I am stuck for a long time, and I wonder what are some good ways to approach this?
I know that we may need to use *ngFor, for example , <li *ngFor="let item of items;"> ....
but there will be a nested for loop which one row can have several options, and sometimes a row only has a option. How can I handle these circumstances?
Can someone give me a hint?
Thank you!
I have updated your mapDatas function:
mapDatas( data: any ){
const dataObj:any = {}
this.fakeData.forEach(data => {
const {display_line_num: key, option_name: value} = data;
dataObj[key] = dataObj[key] ? [...dataObj[key], value] : [value]
});
return Object.values(dataObj);
}
Here we are iterating through the fakeData array and pushing each item's option_name value in a nested array and the index of each array is the display_line_num of each item. So, when more than one element have the same display_line_num, they will be put in the same array.
And finally, we are returning the object converted to an array. Now you can iterate through each item using ngFor in your template.

JavaScript in Vue Component, set Data property in object 1 tp data in object 2 if Key matches

I think I'm close to a solution but I need some help,
I have a form object I want to update where key's match to an imported object.
form.title would be set to the value in article.title.
I have done the following, but am struggling how to set this.form[key][value] to this.article[articleKey][articleValue].
Object.entries(this.form).forEach(([key, value]) => {
Object.entries(this.article).forEach(([articleKey, articleValue]) => {
if ([articleKey][0] === [key][0]){
//[value] = [articleValue];
//this.form[key][value]=this.article[articleKey][articleValue]
}
});
Any help would be appreciated, i'm new to javascript. I can't clone the object as i only want to update the data properties in form and bring across all the data in article object.
Response to comment - example of form
form: new Form({
title: '',
description: '',
earliest_date:'',
latest_date:'',
image_file_names:[]
})
Article Example
{"id":21,
"owner_id":1,
"title":"test1",
"description":"Test It",
"earliest_date":"2020-06-01",
"latest_date":"2020-06-06",
"image_file_names":"[\"1593530083background.jpg\",
\"159353008520190713_085629.jpg\"]",
"physical_description":"Test 1"}
This looks to be working, it felt wrong setting value to the key but its not doing that, it is setting value of that key.
Object.entries(this.form).forEach(([key, value]) => {
Object.entries(this.article).forEach(([articleKey, articleValue]) => {
if ([articleKey][0] === [key][0]){
this.form[key] = [articleValue];
}
});
});

How to map hash pattern to string value?

I want to map what is in the location hash to a string. The mapping has to be based on a pattern below (:Placeholder would be arbitrary numbers, maybe RegEx?). What is the best way to handle this in a function?
'news/:NewsID/dup' => 'newsDuplicate',
'news/:NewsID' => 'newsDetail',
'news/:NewsID/authors' => 'authorsList',
'news/:NewsID/authors/' => 'authorsList',
'news/:NewsID/authors/create' => 'authorsCreate',
'news/:NewsID/authors/:AuthorID' => 'authorDetail',
'news/:NewsID/authors/:AuthorID/orders' => 'orders',
'news/:NewsID/authors/:AuthorID/workflow' => 'workflow',
'news/:NewsID/authors/:AuthorID/tags' => 'tags'
I am trying to highlight the correct button in a navigation and wanted a function like handleNav() which would highlight the right button based on the pattern.
For example, when at http://mydomain.com#!news/123/authors/987, then I can do something like this:
function handleNav() {
var current = ?? //get mapped string above
$('button.' + current).addClass('active').siblings().removeClass('active');
}
How do I get the "current" variable above based on the mapping? Not sure if a bunch of if-else statements would be the best way and I do not know much regex. Thanks for any help or insight.
Perhaps normalize the string before reading the mapping? Something like this:
var map = {
'news/ID/dup' : 'newsDuplicate',
'news/ID' : 'newsDetail',
'news/ID/authors' : 'authorsList',
'news/ID/authors/' : 'authorsList',
'news/ID/authors/create' : 'authorsCreate',
'news/ID/authors/:AuthorID' : 'authorDetail',
'news/ID/authors/:AuthorID/orders' : 'orders',
'news/ID/authors/:AuthorID/workflow' : 'workflow',
'news/ID/authors/:AuthorID/tags' : 'tags'
}
function normalize(str) {
return str.replace(/news\/\d+/,'news/ID')
}
var current = map[normalize(url)];

Categories