Fetching JSON objects based on key values - javascript

This code does a great job of fetching and rendering everything within the JSON array, but what if I am interested in only listing the objects with a particular key-value (like gender)? Would that happen during the fetch or the render?
const URL = "https://ghibliapi.herokuapp.com/people";
const main = document.getElementById("main");
main.innerHTML = "<p>Loading...";
fetch(URL).then((response) => response.json()).then((people) => main.innerHTML = getListOfNames(people));
const getListOfNames = (people) => {
const names = people.map((person) => `<li>${person.name} - ${person.gender} </li>`).join("\n");
return `<ul>${names}</ul>`;
};

The ideal case would be using GraphQL so you only fetch the data fields you need based on your criteria, in this case, there is no difference between changing the getListOfNames function for just outputting a person when its person.gender matches your criteria or simply passing to it a filtered array of people after fetching them all

You would have to configure the api endpoint to accept filters if you'd like to return filtered results. Otherwise, you'd filter on render.
With underscore you'd do _.where(response, {gender: 'male'})

Related

Assign values from one set of key/value pairs to keys of another?

I'm working with the outputs of an Intranet I don't control.
I have this string:
let template = 'LAWYER=|FIRM=|SUIT_DESCRIPTION=|DEF_COMMENT=|PLF_COMMENT=|';
It goes on longer, but that's the pattern.
Now there's another similar string, but with data assigned, as in this example:
let current= 'FIRM=Smith and Wesson LLP|SUIT_DESCRIPTION=It\'s a royal mess|PLF_COMMENT=some freeform text|LAWYER=Bob Smith';
Now, notice that not every element in template is necessarily represented in current, and the order may be different (if the latter fact is a big deal, I can ensure the order is the same).
What I'm trying to do, is take every element that is in current, and populate the matching element in template, if it exists. (or, alternatively and potentially preferred, insert every non-matching element in template into current, but ideally in the same order as template).
Using the date above, the result I'm looking for is:
result = 'LAWYER=Bob Smith|FIRM=Smith and Wesson LLP|SUIT_DESCRIPTION=It\'s a royal mess|DEF_COMMENT=|PLF_COMMENT=some freeform text|';
I'm not very accomplished with JavaScript :(
I tried various things in JSFiddle using split() and match() but I just made a mess of it.
// Convert the template to an array of keys
const getKeys = str => str.split('|').map(entry => entry.split('=')[0]);
// Convert the data to an object
const toObj = str => Object.fromEntries(str.split('|').map(entry => entry.split('=')));
// Reconcile the data with the template
const compile = (templateStr, dataStr) => {
const keys = getKeys(templateStr);
const data = toObj(dataStr);
return keys.reduce((results, key) => {
if(key) results.push([key, data[key] ?? '']);
return results;
}, []);
};
// Convert the results back into a string
const toString = data => data.map(entry => entry.join('=')).join('|') + '|';
// And then a test
let template = 'LAWYER=|FIRM=|SUIT_DESCRIPTION=|DEF_COMMENT=|PLF_COMMENT=|';
let current = 'FIRM=Smith and Wesson LLP|SUIT_DESCRIPTION=It\'s a royal mess|PLF_COMMENT=some freeform text|LAWYER=Bob Smith';
console.log(toString(compile(template, current)));

React JS: How to pass an array from firebase in query parameter?

I'm using multiselection in one of my parameters and I would like to know how to query those parameters like for example if
I want to query parameters that has 1 (doesn't matter if there are other values)
Value one has : 1, 2, 3
Value two has: 5, 1, 6
Value three has: 5, 6, 9
It should only bring Value one and two
I know you can do something like (for non array values):
const librosRef = db.collection('libros');
const queryRef = librosRef.where('grado', '==', '4° Grado');
and it would bring all the documents in that collection that has 4° Grado but if I try to do that while using a multiselection it doesn't bring anything.
This is what I'm trying (doesn't work for array which is what I'm trying to figure out):
const productosRef = db.collection('productosAIB');
const queryRef = productosRef.where('grado', '==', '4° Grado');
useEffect(() => {
queryRef.orderBy("precio")
.get()
.then((snapshot) => {
const tempData = [];
snapshot.forEach((doc) => {
const data = doc.data();
tempData.push(data);
});
setProductos(tempData);
});
}, []);
Example of how it gets stored in the Firebase:
And this is how it looks in the table (without the query because if I add the query it doesn't show anything )
It sounds like you're trying to query for documents based on the existence of a value in an array. These are called array membership queries in Firestore.
For this, you would use array-contains to match a single field in an array, and array-contains-any to match any value from an array.
To query based on single value in array
const queryRef = productosRef.where('grado', 'array-contains', '4° Grado');
multiple values passed in as an array
const queryRef = productosRef.where('grado', 'array-contains-any', ['4° Grado', 'next array element']);
NOTE: array-contains-any can support up to 10 comparison values.
For more information on array membership queries you can see the documentation here

Dynamically populate string literally templates

Whenever I select a person from the list it grabs the id of a name and stores it an array with map.
I then have a string literal which gets populated with the ID.
const id = value.map(person => person.value)
console.log('from',id)
current output:
[u29219]
withe the results looking like this:
const results = await verifiedGet(`get_user/?$u29219?admin_form=True`, user.user)
and then if I add another person the array would look like this
[u29219, u302932]
results:
const results = await verifiedGet(`get_user/hello?$u29219,u302932?admin_form=True`, user.user)
When a user is added to the array I want to be able to iterate through the results with the ID only populating once if a user is selected twice
const results = await verifiedGet(`get_user/?$u29219?admin_form=True`, user.user)
const results = await verifiedGet(`get_user/?$u302932?admin_form=True`, user.user)
is this possible to do so?
I created a sandbox for a better understanding
https://codesandbox.io/s/modest-star-fegy7
I would take your unique id array and use Array.Join() to combine them with commas.
// Map the ids, and filter unique
const uniqueIds = value
.map((person) => person.value)
.filter((value, index, self) => self.indexOf(value) === index);
// Join the Ids and separate them with commas
const commaSeparatedIds = uniqueIds.join[','];
// Don't forget to make them safe for a URL
// You may be able to skip this if you are certain
// your string is safe
const uriSafeIds = encodeURIComponent(commaSeparatedIds);
// Finally, interpolate into your string literal template
// I wasn't sure if the extra $ in your code was intended
// so I left it in.
const url = `get_user/hello?$${uriSafeIds}?admin_form=True`;
const results = await verifiedGet(url, user.user);
In the line const id = user.map((person) => person);, we are looping through the 'user' array and for each iteration, we are just returning the element in that iteration. The 'map' function will return an Array of what will be returned in each iteration. So, basically, we are re-creating the user array in id.
const user = ["u29219", "u302932"];
// 'user' array is re-created here
const id = user.map((person) => person);
console.log("from", id);
const results = `get_user/?${id}admin_form=True`;
If your intention was to form the results string with each element in the array, this would be a way to do it using forEach:
user.forEach((person) => {
const results = `get_user/?${person}$admin_form=True`;
// remaining logic
});
Code-Sandbox
Can make the array unique, then concat or join to get the expected output.
const user = ["u29219", "u302932", "u302932"];
const uniqueItems = [...new Set(user)];
console.log("current uniqueItems", uniqueItems);
let results = "";
uniqueItems.forEach((person) => {
results = results.concat(`get_user/?${person}$admin_form=True `);
});
console.log("current output", results);

firebase -> date order reverse

I am currently making an app using Firebase.
It is one of those bulletin boards that can be seen anywhere on the web.
But there was one problem.
This is a matter of date sorting.
I want to look at the recent date first, but I always see only the data I created first.
postRef.orderByChild('createData').startAt(reverseDate).limitToFirst(1).on('child_added',(data)=>{
console.log(data.val().name + data.val().createData);
})
result - >hello1496941142093
My firebase tree
My code is the same as above.
How can I check my recent posts first?
How Do I order reverse of firebase database?
The Firebase Database will always return results in ascending order. There is no way to reverse them.
There are two common workaround for this:
Let the database do the filtering, but then reverse the results client-side.
Add an inverted value to the database, and use that for querying.
These options have been covered quite a few times before. So instead of repeating, I'll give a list of previous answers:
Display posts in descending posted order
Sort firebase data in descending order using negative timestamp
firebase sort reverse order
Is it possible to reverse a Firebase list?
many more from this list: https://www.google.com/search?q=site:stackoverflow.com+firebase+reverse%20sort%20javascript
You can simply make a function to reverse the object and then traversing it.
function reverseObject(object) {
var newObject = {};
var keys = [];
for (var key in object) {
keys.push(key);
}
for (var i = keys.length - 1; i >= 0; i--) {
var value = object[keys[i]];
newObject[keys[i]]= value;
}
return newObject;
}
This is how I solved it:
First I made a query in my service where I filter by date in milliseconds:
getImages (): Observable<Image[]> {
this.imageCollection = this.asf.collection<Image>('/images', ref => ref.orderBy('time').startAt(1528445969388).endAt(9999999999999));
this.images = this.imageCollection.snapshotChanges().pipe(
map(actions => actions.map(a => {
const data = a.payload.doc.data() as Image;
const id = a.payload.doc.id;
return { id, ...data };
}))
);
return this.images;
}
Then to get the newest date first I added this to my component where I call the method from my service:
let date = new Date;
let time = 9999999999999 - date.getTime();
console.log(time);
I pass the time let as the date. Since a newer date will be a bigger number to deduct from the 9999999999999, the newest date will turn up first in my query inside my service.
Hope this solved it for you
If you want to display it in the front end, I suggest that after you retrieve the data, use the reverse() function of JavaScript.
Example:
let result = postRef
.orderByChild("createData")
.startAt(reverseDate)
.limitToFirst(1)
.on("child_added", data => {
console.log(data.val().name + data.val().createData);
});
result.reverse();
Ive ended changing how I create my list on the frontend part.
was
posts.add(post);
changed to
posts.insert(0, post);
You could use a method where you save the same or alternate child with a negative value and then parse it.
postRef.orderByChild('createData').orderByChild('createData').on('child_added',(data)=>{
console.log(data.val().name + data.val().createData);})
Far more easier is just use Swift's reversed():
https://developer.apple.com/documentation/swift/array/1690025-reversed
https://developer.apple.com/documentation/swift/reversedcollection
let decodedIds = try DTDecoder().decode([String].self, from: value)
// we reverse it, because we want most recent orders at the top
let reversedDecodedIds = decodedIds.reversed().map {$0}
orderBy("timestamp", "desc")
I think you can give a second argument name "desc".
It worked for me

How to "synchronize" Observables?

I have this piece of code:
ngOnInit(): void
{
this.categories = this.categoryService.getCategories();
var example = this.categories.flatMap((categor) => categor.map((categories) => {
var links = this.categoryService.countCategoryLinks(categories.id)
.subscribe(valeur => console.log(valeur));
return categories.id
}));
}
The result are two observables.
One consists in a list of categories.
The second one is the number of items for a particular categories.id.
My question is as follow:
How could I get all this information structured in a particular data structure?
I would like to store categories and the number of items per category in the same data structure to be able to show them up in my TS component.
I went step by step trying to fix my issues and I went to have the following code that is almost the solution:
this.categories = this.categoryService.getCategories();
var example = this.categories.mergeMap((categor) => categor.map((myCateg) =>
{
this.categoryService.countCategoryLinks(myCateg.id)
.map(numlinks => Object.assign(myCateg,{numLinks: numlinks}))
.subscribe(valeur => console.log(valeur));
return myCateg.id
}));
It gives the following output:
Where numLinks is still an object... (containing my count value) Any idea on how to transform it to a json property like categoryName or id??
Thanks in advance and Regards,
Here is the solution to the problem:
ngOnInit(): void
{
this.categories = this.categoryService.getCategories();
const example = this.categories
.mergeMap((categor) => categor
.map((myCateg) => {
this.categoryService.countCategoryLinks(myCateg.id)
.map(numlinks => {
myCateg.numlinks = numlinks.count;
return myCateg;
})
//Object.assign(myCateg,{numLinks: numlinks}))
.subscribe(value => console.log(value));
return myCateg
}));
example.subscribe(val => console.log("value2: "+val));
}
Once more, the solution comes from the mergeMap() operator. :-)
this.categoryService.getCategories()
.mergeMap(val => val) // "Flatten" the categories array
.mergeMap(category =>
this.categoryService.countCategoryLinks(category.id)
// Write the number of links on the `category` object
.map(numLinks => Object.assign(category, {numLinks: numLinks}))
)
.toArray()
.subscribe(allCategoriesWithNumLinks => console.log(allCategoriesWithNumLinks));
I'm not going into the specifics (the first mergeMap to flatten the array, Object.assign() to produce the final object) since it seems like we covered all that in a previous thread we had, but feel free to ask questions if anything is unclear.
Philippe's questions:
Why flatten the categories array? I'm assuming getCategories() emits a SINGLE array containing all the categories. Since you want to run an HTTP request for each category, it's more convenient to have an observable emitting each category individually. That's what the first mergeMap() does: it transforms Observable<Category[]> into Observable<Category>.
Why create an object? You said you wanted to store everything in the same data structure. That's what Object.assign does: it writes the number of links found for each category on the category object itself. This way, you end up with ONE object containing the information from TWO observables (category + numLinks).

Categories