Accessing the first value of the first key in an object - javascript

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

Related

How to use array.push to add value to an array?

I would like to add a value with array.push to my first element of array [0] to the field yesterday, I don't know very well what the structure is to be able to add this value. try the following way
var cumpleaños = [
{
ayer: "",
},
{
hoy: "12-07-20",
} ,
{
mañana: "12-08-20"
}
];
cumpleaños.push([0].ayer.("12-06-20"))
console.log(cumpleaños[0].ayer)
Thank you very much for the help!
You don't need to push anything since you're not adding a new value, you're just modifying an existing value:
cumpleaños[0].ayer = "12-06-20";
As a side note, your data structure would be much more effectively represented by a single object not inside an array:
const cumpleaños = {
ayer: "12-06-20",
hoy: "12-07-20",
mañana: "12-08-20"
};
You would do assignment to the first element of the array. (If the oder is always the same)
cumpleaños[0].ayer = "12-06-20"

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

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.

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

Search Function on AngularFireList in Ionic

I am having a bit of trouble wrapping my head around getting this search function to work. I have it setup right now so it will get the right item when I search it but it's spelling has to be exact including capitalization and punctuation. I want it to be able to get the item regardless of the users search term's capitalization and if they just typed the letter 'b' it will include all items that have a 'b' in the items fields.
I know that I want to query the call to the database since it would be quite heavy to do it on the client side but what do you guys think or how would you go about achieving this?
setFilteredItems() {
this.employeeListRef = this.database.list('userProfile',
ref=> ref.orderByChild('lastName'));
this.employeeList = this.employeeListRef.snapshotChanges()
.map(
changes => {
return changes.map(c => ({
key: c.payload.key, ...c.payload.val()
}))
}
);
//if searchterm is null it returns so it can set back the list to all values
//searchterm is declared in constructor
if(!this.searchTerm) {
return;
}
//var term = this.searchTerm.toLowerCase();
this.employeeListRef = this.database.list('userProfile',
ref => ref.orderByChild('lastName').equalTo(term));
this.employeeList = this.employeeListRef.snapshotChanges()
.map(
changes => {
return changes.map(c => ({
key: c.payload.key, ...c.payload.val()
}))
}
);
}
If you look at the ASCII table you can get a good idea of how Firebase stores it's records and why orderByChild might not work as you expect.
b is 98 and B is 66. Their in different positions on the ASCII table.
There are two things you can try to help you access the data in the expression you want.
Try converting the searchable data to lowercase with the user of database methods
Use a cloud function and on-write of a record, save a lowercase version of that record in the object, then search by that record. An example would be;
{ lastName: 'Smith', lowercaseLastName: 'smith' }
You then orderByChild('lowercaseLastName').

Javascript/Ramda: How to make the following code functional

Hi I have the following object structure,
const usersList = {
NFr9F4WbBxR4H5ajolbS6q0skPF2: {
name: "justin davidson",
uid: "NFr9F4WbBxR4H5ajolbS6q0skPF2"
},
asas9F4WbBxR4H5ajolbS6q0sasF2: {
name: "sawyer davidson",
uid: "asas9F4WbBxR4H5ajolbS6q0sasF2"
}
}
It has a user ID as key, and it's user object nested within. I want to store the inner user data. I've been using Ramda JS and have done so by doing the following,
let x = []
const y = R.keys(usersList).forEach((uid) => {
x.push(usersList[uid])
return x
})
which returns
[{"name":"justin davidson","uid":"NFr9F4WbBxR4H5ajolbS6q0skPF2"},
{"name":"sawyer davidson","uid":"asas9F4WbBxR4H5ajolbS6q0sasF2"}]
..however I'd like achieve the same in a purely functional way. What would be the best approach here? I'm guessing compose and map but I can't seem to work it out. Looking for a little direction.
Thanks
Just use map instead of forEach:
const x = R.keys(usersList).map((uid) => usersList[uid])
It looks like there's also a values method that does what you want:
const x = R.values(usersList)
There isn't always a function tucked away in some lib that does exactly what you want it to do. Showing how to do things on your own demonstrates that you don't have to feel "stuck" when you're faced with a problem and you can't find a magical function to solve it for you. Once you learn the function exists, sure, go ahead and replace your home-brew solution with the built-in. But until then, don't be afraid to write code and move on.
// ovalues :: (Object k:v) -> [v]
const ovalues = o =>
Array.from(Object.keys(o), k => o[k])
const usersList = {
NFr9F4WbBxR4H5ajolbS6q0skPF2: {
name: "justin davidson",
uid: "NFr9F4WbBxR4H5ajolbS6q0skPF2"
},
asas9F4WbBxR4H5ajolbS6q0sasF2: {
name: "sawyer davidson",
uid: "asas9F4WbBxR4H5ajolbS6q0sasF2"
}
}
console.log(ovalues(usersList))
So yep, R.values does exist in the Rambda library, but next time don't be afraid to try to solve it on your own. You have a powerful brain, now use it ^_^

Categories