How to search array of object in backbone js - backbone.js

how to search array of object in backbone js.The collection contain persons model.
[{
name: "John",
age: "18",
likes: {
food: "pizza",
drinks: "something",
}
},
......
]
how can i get persons who likes something.
i did try collection.where({likes :{food : "pizza"}});

Since your food property is in an object on the Person's attributes, using where (which by default just looks at the flat attributes) isn't going to work. You can use the filter method to apply a truth test to all of the items in your collection and just get the ones that pass.
In the code you posted, it doesn't look like you have a Backbone Collection proper, just a regular array of objects.
Since Underscore is on the page, you can use it to help filter through your list.
var people = [
{
name: "John",
age: "18",
likes: {
food: "pizza",
drinks: "something",
}
},
......
];
var likesPizza = _.filter(people, function(person) {
return person.likes.food === "pizza";
});
If it is in fact a Backbone Collection, you can use
this.collection.filter(people, function(person) {
return person.get('likes').food === "pizza";
});

Related

How to generate an array of objects in Alpine.data with Livewire Eloquent collection and Adding properties in those js objects

and thanks for your attention and help,
I have a Collection in my livewire controller. This collection contains a list of players, with some properties : here we will just focus on id and name.
So we can imagine that we have 3 players in the collection :
Players[0] : 'id'=>1, 'name'=>'Yann';
Players[1] : 'id'=>2, 'name'=>'Robert';
Players[2] : 'id'=>3, 'name'=>'Jessica';
I need to get these players in my alpine data.
I can easily get these players in Alpine with the #js method :
window.addEventListener('alpine:init', () => {
Alpine.data('data', () => ({
players: #js($players),
}))
})
So, now I have in my alpine.data :
players: [
{ id: 1, name: 'Yann' },
{ id: 2, name: 'Robert' },
{ id: 3, name: 'Jessica' },
]
Now I can easily display the players in my html with a template x-for :
<template x-for="player in players">
<p x-text="player.name"></p>
</template>
But I want to add some additionnal properties in each player object. Those properties will be updated in front depending user's actions.
I would like to get something like this :
players: [
{ id: 1, name: 'Yann', touched20: 0, touched15: 0 },
{ id: 2, name: 'Robert', touched20: 0, touched15: 0 },
{ id: 3, name: 'Jessica', touched20: 0, touched15: 0 },
]
All additionnal properties are the same for each object in the array, so I imagine i could use a foreach loop to put them in the objects.
But I can't see and don't understand how i can include a loop in my alpine.data script to do this.
Anyone could help me ?
I edit my question because I found a solution :
I just make a loopPlayers function outside of my alpine data and call this function in the alpine data :
function loopPlayers() {
let players = [];
const livewirePlayers = #js($players);
livewirePlayers.forEach(element => {
players.push(element);
});
players.forEach(function(element) {
element.touched15 = 0;
})
return players;
}
And in alpine.data :
players: loopPlayers(),
Now I have my collection of players from my livewire controller & I have new properties for each element of the collection in the js data
That was easy, as usual I guess :)

filter array elememts to add to listView

I am reading from my firebase database, which holds nested data in the following format which I want to add specific elements of to a listView;
group {
subgroup {
index[0]{
name: "Tom"
message: "hello"
}
index[1]{
name: "Dave"
message: "goodbye"
}
index[2]{
name: "Katie"
message: "morning"
}
}
}
What I want to do is add the name and message property to a listView in my app, an array is created when my app is launched with data from firebase, so I need to check for the name property and add to the list view when applicable.
I have used for loops and image visibility to display markers on a calendar, would a similar approach of looping through the array be the best option to create the list? I do need to create the list on specific dates on the calendar with 1 or more username entry in the same method.
By looping using the following code in my console shows what i want. yet i am struggling to translate into my list model, If i am just adding the name the below code works, but adding both to my list isn't working. My code is;
var nameArr = (JSON.stringify(value))
var parseData = JSON.parse(nameArr);
for(var index in parseData)
console.log("nameParse: ", parseData[index].name, ":", "detailsParse: ", parseData[index].message)
ListView {
id:eventListView
spacing: 4
clip: true
anchors.fill: parent
anchors.margins: 10
model: ListModel {id: model }
Component.onCompleted: {
model.clear();
var list = parseData;
for(var i in list)
model.append({"name": list[i].name, "details": list[i].message});
}
delegate: Label {
id: nameLabel
text: modelData.name
}
Label {
id: timeLabel
text: modelData.message
}
}
Javascript array could be used as a data source in this way:
ListView {
anchors.fill: parent
property var group: {
"subgroup": [
{
"name": "Tom",
"message": "hello"
},
{
"name": "Dave",
"message": "goodbye"
},
{
"name": "Katie",
"message": "morning"
}
]
}
model: group.subgroup
delegate: Text { text: modelData.name }
}

How to loop through an array of objects using angularjs

I am working on an ionic app that loads data from firebase. In this case I have a .factory called NoteStore that reads a specific table in firebase (eg "lakes").
{
"lake": {
"one": {
"bio": "xxxx",
"shortname": "xxxx",
"name": "xxxxx",
"reknown": "xxxx",
"image":"xxxxx"
},
"two": {
"bio": "xxxx",
"shortname": "xxxx",
"name": "xxxxx",
"reknown": "xxxx",
"image":"xxxxx"
}
}
}
This is the .factory code that reads from firebase:
//get all lake activites
getAllLakes: function(){
return $firebaseArray(ref.child('lake'));
},
//get individual lake activites
getLake: function(lakeId){
return $firebaseObject(ref.child('lake').child(lakeId));
}
My app Controller then gets the data through the NoteStore and calling a function "getAllLakes():
app.controller('LakeActivitiesListController', function($scope, NoteStore, $localStorage) {
$scope.alllakes = NoteStore.getAllLakes();
}
The main problem is that I want to access individual objects from the "lake" table in firebase so that I can be able to store them in localStorage.
This then displays array of objects as below:
When I just create an object as shown below and save to localStorage, it works fine, as shown in the image below.
var myObj = [
{
name: 'james',
title:'doctor'
},
{
name: 'jojo',
title:'doctor'
}
];
console.log(myObj);
//
window.localStorage['lakes'] = JSON.stringify(myObj);
$scope.data = JSON.parse(window.localStorage.getItem('lakes'));
I am working on my college project that is overdue. Please help. All I want is to be able to access an array that contains objects from firebase so that I can store them in localStorage.
Please.
angular.forEach is the way, here is an example:
Example with array of objects iteration:
var array_of_objects = [{name: 'Jimi', gender: 'male'},{name: 'Peter', gender: 'male'},{name: 'Bob', gender: 'male'}];
angular.forEach(array_of_objects, function(item, index) {
console.log(item, index);
});
Example with object iteration:
var my_object = {name: 'Jimi', gender: 'male', age: '25'};
angular.forEach(my_object, function(value, key) {
console.log(value, key);
});
In your case you want to make an angular.forEach on $scope.alllakes and then push the object that you want in the storage
The problem is, that you have an object not an array. You can loop through the different members of you object with
for(var propertyName in myObject) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
}

Angular filter by array that contains search criteria

Does the built in Angular "filter" support filtering an array in the sense that "filter where array contains "
Such as follows:
$scope.currentFilter = "Allentown";
$scope.users = [{
name: "user1",
locations: [
{ name: "New York", ... },
{ name: "Allentown", ... },
{ name: "Anderson", ... },
]
}, ... ];
<div ng-repeat="user in users | filter : { locations: { name: currentFilter } }"></div>
In other words I'm looking to filter to only users with a "locations" array that CONTAINS a location that matches the string by name.
If not, how can I accomplish this with a custom filter?
Your code snippet works as is since Angular 1.2.13. In case you're using an older version (tested on 1.0.1) and don't need to reuse your filtering routine across controllers (in which case you should declare a proper filter), you can pass the built-in filter a predicate function :
<div ng-repeat="user in users | filter : hasLocation">{{user.name}}</div>
And write something like this :
$scope.currentFilter = "Allentown";
$scope.hasLocation = function(value, index, array) {
return value.locations.some(function(location) {
return location.name == $scope.currentFilter;
});
}
Fiddle here.

How to get a valid filtered model from a Backbone Collection?

I'm sure I make one of these Backbone newbie mistakes but after a hour of searching around I didn't found a solution.
Here's the problem: When I try to get a filtered model from my collection theres a type error "productCollection.getProductByName("M020012").toJSON is not a function".
But if I change the filter method to a simple "return this.at(0)" I get a valid model.
Why is that and what is the solution?
Here's the JSFiddle
var products = [{
"name": "M020013",
"gender": "M",
"pictures": [{
"picture": {}}]},
{
"name": "M020012",
"gender": "M",
"pictures": [{
"picture": {}}]},
{
"name": "M020011",
"gender": "M",
"pictures": [{
"picture": {}}]}
];
var Product = Backbone.Model.extend({});
var ProductCollection = Backbone.Collection.extend({
model: Product,
getProductByName: function(productName) {
//return this.at(0);
return this.filter(
function(product) {
return product.get('name') === productName;
});
}
});
var productCollection = new ProductCollection();
productCollection.on('reset', function() {
console.log('reset');
console.log(productCollection.getProductByName('M020012'));
console.log(productCollection.getProductByName('M020012').toJSON());
});
productCollection.reset(products);
It's because filter returns an array of models. And an Array in javascript does not have a toJSON function.
Since you want to return a model instead of an array, then you can use the find in place of filter. The find method returns the first model that matches the criteria
Here's what the code would look like:
getProductByName: function(productName) {
return this.find(function(production) {
return production.get('name') === productName;
});
}

Resources