Backbone - How can I slice a collection? - backbone.js

I've got a Backbone Collection. How can I slice the collection, or at least truncate the list to a certain length?

Assuming that you have your collection defined and initialized and that you want to mutate the collection (change it in place) you have to do:
collection.reset(collection.first(n));
of you can use .last(n) to get last N elements.
If you just wanted to get the first n elements without modyfying the collection just do:
var models = collection.first(n);
Here is a list of all the underscore methods you can use directly on your collection.

Related

Firebase Firestore: Append/Remove items from document array

I am trying to append/remove items from an array inside of a Firestore Document but every time the entire array is replaced instead of the new value being appended. I have tried both of the following:
batch.setData(["favorites": [user.uid]], forDocument: bookRef, options: SetOptions.merge())
batch.updateData(["favorites": [user.uid]], forDocument: bookRef)
I know that instead of an array I can use an object/dictionary but that would mean storing additional data that is irrelevant (such as the key), all I need is the ID's stored inside the array. Is this something that is currently possible in Firestore?
Update elements in an array
If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present. arrayRemove() removes all instances of each given element.
let washingtonRef = db.collection("cities").document("DC")
// Atomically add a new region to the "regions" array field.
washingtonRef.updateData([
"regions": FieldValue.arrayUnion(["greater_virginia"])
])
// Atomically remove a region from the "regions" array field.
washingtonRef.updateData([
"regions": FieldValue.arrayRemove(["east_coast"])
])
See documentation here
Actually, nowadays it is possible. With latest updates db.collection.updateData
method actually appends new item to array instead of replacing it.
Example usage can be found in Firebase documentation.
If you need to do it manually, you can use
FieldValue.arrayUnion([user.uid])
Nope. This isn't possible.
Arrays tend to be problematic in an environment like Cloud Firestore where many clients could theoretically append or remove elements from an array at the same time -- if instructions arrive in a slightly different order, you could end up with out-of-bounds errors, corrupted data, or just a really bad time. So you either need to use a dictionary (where you can specify individual keys) or replace the entire array.

Order collection of array objects

After making some queryes i have a collection of array objects. But after orderByDesc the data transform in hole objects, instead of how it was (array of objects), what it happened? Is like the method orderByDesc tranform the collection in another type.
Ex:
some logic code, queries...etc
in the end
return $total->sortByDesc('date');
After using sortByDesc:
Before to sortByDesc:
Now that is in type of objects is giving some issues working with it in my javascript application (angularjs), it not a array of objects how should it be.
Try to copy the collection when sorting and use values()
$sorted = $total->sortByDesc('date');
dd($sorted->values());
Same result?

How do I modify/enrich an Eloquent collection?

I'm using eloquent relationships.
When I call $carcollection = $owner->cars()->get(); I have a collection to work with. So let's say that I have, for this particular owner, retrieved three cars. The collection is a collection of three arrays. Each array describes the car.
This is all working fine.
Now I want to add more attributes to the array, without breaking the collection. The additional attributes will come from a different source, in fact another model (e.g. servicehistory)
Either I retrieve the other model and then try merge() them, or I try manipulate the arrays within the collection without breaking the collection.
All this activity is taking place in my controller.
Is one way better than another, or is there a totally different approach I could use.... perhaps this logic belongs in the model themselves? Looking for some pointers :).
Just to be specific, if you do $owner->cars()->get(); you have a collection of Car Models, not array.
That have been said, you can totally load another relation on you Car model, using
$carcollection = $owner->cars()->with('servicehistory')->get();
$carcollection->first()->servicehistory;
You can try to use the transform method of the collection.
$cars = $owner->cars()->get();
$allServiceHistory = $this->getAllService();
$cars->transform(function($car) use($allServiceHistory) {
// you can do whatever you want here
$car->someAttribute = $allServiceHistory->find(...):
// or
$car->otherAttribute = ServiceHistoryModel::whereCarId($car->getKey())->get();
});
And this way, the $cars collection will be mutated to whatever you want.
Of course, it would be wiser to lazy load the data instead of falling into an n+1 queries situation.

filtering for max value in collection in backbone.js

I have a collection of models having structure:
{"name":"xyz","company":"abc","recNumber":"M34/14-15/23"}
I need to get that specific model from this collection whose recNumber is highest(based on number after last slash). I guess it can be done with .filter from underscore but don't know what will be the exact construct in this case.
try this;
model = collection.max(function(m){
return _.last(m.get('recNumber').split('/'));
});
collection.max() Returns the maximum value in list.
_.last(array) Returns the last element of an array.
jsfiddle here

replace collection in a view

I want to replace a collection inside a view. I use the reset command like this:
var maColl=mContent.get(ici).get("svgParameterList");
msvgParameterListView.collection.reset(maColl);
A JSON.stringify gives this :
maColl
[{"id":"x","name":"x"},....{"id":"style","name":"style"}]
msvgParameterListView.collection
[[{"id":"x","name":"x"},....{"id":"style","name":"style"}]]
Now, i have my collection in an array, so when i render it return null value.
How to change array of collection into collection ?
In short, how to make msvgParameterListView.collection equal to maColl ?
Note the [[ ]] for the new collection.
Note maColl is a collection inside another collection.
If I understand correctly, you are trying to reset a collection with the models of another collection? collection.toJSON is your friend:
toJSON collection.toJSON()
Return an array containing the attributes hash of each model in the collection. This can be used to
serialize and persist the collection as a whole. The name of this
method is a bit confusing, because it conforms to JavaScript's JSON
API.
which could be applied like this
msvgParameterListView.collection.reset(maColl.toJSON());
Or if you want to keep a reference to the original models, pass maColl.models
msvgParameterListView.collection.reset(maColl.models);
Passing directly a collection to reset will only confuse Backbone.

Resources