var collection = new Backbone.Collection([
{key:1,name: "Tim", age: 5},
{key:2,name: "Ida", age: 26},
{key:3,name: "Rob", age: 55}
]);
i am going to add the model
{key:4,name: "Rob", age: 55}
Here since the key is different, backbone will not give an error. How do I check for an existing model in the collection before adding?
A Backbone model has a concept of an idAttribute (http://backbonejs.org/#Model-idAttribute) that is used for duplicate checking when adding to a collection.
This may not work for you because it seems your idAttribute would be 'key' which is continuously incrementing.
Instead you could check in code via:
var newModel = {key:4,name: "Rob", age: 55};
var similarModel = collection.findWhere({name: newModel.name, age: newModel.age});
if(!similarModel) {
//add to collection
}
Related
I am reduce an array of object into a single object that should look like this :
`
result = {
23 : [{obj of kyle}, {obj of jade}],
29 : [{obj of ruby}]
32 : [{obj of mat}]
}
`
I have used reduce to do this, each person variable will refer to an object of the array to reduce, and they all collapse into a single object refered to with the variable group, the initial value of that object is an empty object {}, so with an if statement i checked first if it's empty, then create a key named age with a new empty array as value and push the person object into that empty array, and if the key age exists, then skip the new array creation and push that corresponding person object into the corresponding array.
what's wrong with this code?
`
const people = [
{name: "kyle", age: 23},
{name: "jade", age: 23},
{name: "ruby", age: 29},
{name: "mat", age: 32}
]
let result = people.reduce(function(person, group){
const age = person.age;
if(group[age]==null){
group[age] = []
}
group[age].push(person);
return group
},{})
console.log(result);
`
not what i expected
Looking again at your code it seems that you can fix your own code by replacing person and group in your callback function inside reduce like so
const people = [
{name: "kyle", age: 23},
{name: "jade", age: 23},
{name: "ruby", age: 29},
{name: "mat", age: 32}
]
let result = people.reduce(function(group, person){
const age = person.age;
if(group[age]==null){
group[age] = []
}
group[age].push(person);
return group
},{})
console.log(result);
You can do something like this as well
const people = [
{name: "kyle", age: 23},
{name: "jade", age: 23},
{name: "ruby", age: 29},
{name: "mat", age: 32}
];
const result = people.reduce((acc, curr) => {
if (!acc[curr.age]) {
return {...acc, [curr.age]: [curr]}
}
return {...acc, [curr.age]: [...acc[curr.age], curr]};
}, {});
console.log(result);
What we did here is initiating it with a new object like you did, then for each element in the array denoted as curr for current we check if our new object (denoted as acc for accumulator) has a key with this age already of curr.age. If not we make an array for this age and put the current element inside.
Else, if this age key already exist just add to that age array the current element.
I am using the new hooks version of react-table. I have data like this:
data: const persons = [{name: 'Ram', age: 15 }, {name: 'Shyam',
age: 18 }, {name: 'Hari', age: 20 }]
I would like to filter the persons by age. I used setAllFilters() function to filter.
For filtering persons whose age is 15,
setAllFilters({age: 15})
just works.
However, I would like to filter all the persons whose age is 15 or 18. How would it be possible ?
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";
});
I am trying to add a couple of models to the collection
rolesSuccess: function(roles) {
var role1 = new Role({
id: "1",
Name:"TST1",
Description:"Test 1"
});
var role2 = new Role({
id: "2",
Name:"TST2",
Description:"Test 2"
});
roles = new Roles();
roles.add(role1);
roles.add(role2);
this._context.roles(roles);
}
I only see one role being added at any point, just the first one. What am I doing wrong?
you can pass an array of models to a backbone collection when you initialize it.
var roles = new Roles([role1, role2]);
Problem
When a child model is initialized for the first time, only defaults of the child are set as attributes.
When a second(and all subsequent) child is being initialized, the attributes of child display defaults of child and it's parent.
Fiddle
var Parent = Backbone.Model.extend({
defaults: {
name: "john",
lname: "smith",
age: 30,
language: "english",
location: "belgium"
}
});
var Child = Parent.extend({
defaults: {
hobby: "doing nothing",
age: 24,
occupation: "student"
},
initialize: function () {
this.constructor.__super__.initialize.apply(this, arguments);
_.defaults(this.defaults, this.constructor.__super__.defaults);
console.log(this.attributes);
}
});
attributes of child initialized for the first time :
var child1 = new Child();
child1.attributes :
hobby: "doing nothing"
age: 24
occupation: "student"
attributes of same Child class, initialized for the second time:
var child2 = new Child();
child2 attributes:
age: 24
hobby: "doing nothing"
language: "english"
lname: "smith"
location: "belgium"
name: "john"
occupation: "student"
Question
Why are not all defaults(child's and parent's) are being set as attributes when a child model is initialized for the first time ?
Because i've to display a Backbone.Collection inside a <ul> and every model's attributes are configurable through a html form inside each <li>. But because of this problem, i can't get to all attributes of the first model in the collection.
You're modifying the Child class's defaults object when the first object is instantiated, during its initialize method. At that point, the Backbone.Model constructor has already used defaults to fill in the attributes for that object, so it will only affect subsequent instantiations.
Take a look at Backbone.Model:
var Model = Backbone.Model = function(attributes, options) {
var defaults;
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
_.extend(this, _.pick(options, modelOptions));
if (options.parse) attrs = this.parse(attrs, options) || {};
if (defaults = _.result(this, 'defaults')) {
attrs = _.defaults({}, attrs, defaults);
}
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
};
initialize is the very last step, after the defaults have been set, so modifying defaults at that point won't do anything for the current object.
To get it to work how you want, modify defaults after you declare the class, rather than during initialize:
Child.prototype.defaults = _.defaults(Child.prototype.defaults, Parent.prototype.defaults);
Working example