Sorting a nested array from model in Ember? - arrays

So I have a model in Ember that is generating a hash with three objects. One of the objects is an array of objects with another array inside each object. I need to sort this innermost array, but I am having trouble doing so.
Here are my models.
App.Person = DS.Model.extend ({
first_name: DS.attr('string'),
last_name: DS.attr('string'),
age: DS.attr('string'),
gender: DS.attr('string'),
innerMostArray: DS.hasMany('innerMostObject')
});
App.innerMostObject = DS.Model.extend ({
person_id: DS.belongsTo('person'),
attr1: DS.attr('string'),
attr2: DS.attr('string')
});
Here is my Route
App.NestedArrayRoute = Ember.Route.extend({
model: function(params) {
return Ember.RSVP.hash({
object1: this.store.find('object1', params.object1_id),
people: this.store.all('person'),
object3: this.store.all('object3')
});
},
afterModel: function(model, transition) {
model.people.forEach(function(item, index, enumerable){
var innerMostArray = item.get('innerMostArray');
var sortedArray = innerMostArray.sortBy('attr1', 'attr2');
});
model.people.update();
}
});
I know that I am nowhere near doing this right but I just don't know how to sort this nested array. I've seen examples of array controllers, but I don't know how to use one to sort this nested array. If anyone could give an example of how to do this it would be very helpful. Thank you.

I agree with Kalmans answer, but I suggest you do this sorting with built-in methods to save you trouble:
App.Person = DS.Model.extend({
name: DS.attr('string'),
fruits: DS.hasMany('fruit', {async: true}),
fruitSorting: ['title', 'color'],
sortedFruits: Ember.computed.sort('fruits', 'fruitSorting')
});
I forked his example here: http://emberjs.jsbin.com/manutu/1/edit?html,js,output

One way to do this is to create a computed property on the model as follows:
App.Person = DS.Model.extend({
name: DS.attr('string'),
fruits: DS.hasMany('fruit', { async: true }),
sortedFruits: function(){
var fruits = this.get('fruits');
return fruits.sortBy('title', 'color');
}.property('fruits.#each.title', 'fruits.#each.color')
});
Working example here

Related

How to convert an array of dictionaries into an array of keys using react

Given a list:
let names = [{name: "bobby"}, {name: "sydney"}, {name: "Paul"}, {name: "Grace"}
I want the output to be ["bobby", "sydney", "Paul", "Grace"]
Here is what I have tried:
var items = Object.keys(names).map(function(i) {
return names[i];
})
const items = Object.keys(names).map((key)=>names[key]);
this.setState({items});
console.log(this.state.items);
names.map(({ name }) => name)
const names = [{
name: "bobby"
}, {
name: "sydney"
}, {
name: "Paul"
}, {
name: "Grace"
}];
const keys = names.map(({
name
}) => name);
console.log(keys);
A note about react keys, they should be unique within the rendered siblings, i.e. they should be unique within the dataset. Names alone may not provide sufficient uniqueness.
A second note, you might not want to generate your react keys separately from where you need them, i.e. generally they are created when you are mapping JSX.
This is not really related to React. You can do that with JavaScript, for instance using API like map().
Here is an example:
let arr = names.map(obj => obj.name);

How can I declare a two dimensional array in React?

I try to do this:
getInitialState: function(){
return({
people: [] .... or people: [{id: "", key: ""}] or people: [[id: ][key: ]]
});
},
so I have an id and a key every person and I want to store it like this.
Looks like a syntax error. Try:
getInitialState () {
return {
people: []
};
}
This creates an empty array in your initial state. You can just populate your people array normally like so:
let p = this.state.people.slice();
p.push({id: "", key: ""});
this.setState({people: p});
The first line creates a copy of your people. You then push a new item to the temporary array. Finally you replace the old people state with the new one.
A one-liner way of doing this:
this.setState({people: this.state.people.concat([{id: "", key: ""}])});

Object changes when selected with setState

I made a question earlier which is mostly confused nonsense
(Mongoose, array in object)
Now I Think I have narrowed it down to the following:
I have a list of drivers which has an Array of cars:
var driverSchema = new mongoose.Schema({
driver: String,
age: String,
cars: [{ type: Schema.Types.ObjectId, ref: 'Car' }]
});
module.exports = mongoose.model('Driver', driverSchema);
A driver-object can be selected to ChoosenDriver like so:
this.setState({choosenDriver:driver})
The problem is that the object Changes when selected. It changes from this:
drivers: array[3]
->0: {}
->1: {}
_v: 0
_id: "4242594395935934"
name: "Roger"
cars: Array[1]
to this:
choosenDriver: {..}
_v:0
_id: "235345353453"
name: "Roger"
cars:
->_proto_ :{..}
0: "4242594395935934",
_id: undefined
cars is no longer an Array when the driver is selected.
Anyone run into something similar maybe?
Update:
I pass the list of drivers to a Child Component like this:
<DriversList drivers={this.props.drivers}
In DriversList i select a driver like this:
(render-func should be enough to show you)
handleDriverClick: function(i) {
this.props.setChoosenDriver(this.props.drivers[i])
},
render: function(){
var self = this;
var drivers = this.props.drivers.map(function(driver,i){
return <li key={driver._id} onClick={self.handleDriverClick.bind(null, i)}> {driver.name} </li>;
});
And in the Parent :
setChoosenDriver: function(driver) {
this.props.setChoosenDriver(driver)
},
And finally in the GrandParent i set the state:
setChoosenDriver: function(driver) {
this.setState({choosenDriver:driver})
},
Update:
getInitialState: function() {
return {
drivers:[]
};
},
componentWillMount: function(){
var self = this;
request
.get(Driversurl)
.end(function(err, res){
self.setState({drivers: res.body});
});
},
Its an Array of drivers wtih objects like:
{"_id":"5607b0747eb3eefc225aed61","name":"Moore","__v":0,"cars":["5607b0747eb3eefc225aed61","5607b07a7eb3eefc225aed62","5606bf4b0e76916c1d1668b4","5607b07a7eb3eefc225aed62"]}
don't execute your request in componentWillMount this is really wrong , execute it in componentDidMount, see this for more details : bind(this) not working on ajax success function
Also I would parse you request result when you receive it, your problem may come from here
self.setState({drivers:JSON.parse(res.body)});

How to search array of object in 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";
});

Merge local Backbone collection with server

I have a local Backbone collection:
var collection = new Backbone.Collection([ { greeting: "hi" }, { greeting: "bye" } ]);
I understand that when I run collection.fetch, Backbone will run collection.set on the results. I need to merge in the response from the server, however. Say the response is:
[ { id: "2", greeting: "hi", name: "Bob" } ]
I would like the resulting collection, after the merge, to be:
[ { id: "2", greeting: "hi", name: "Bob" }, { greeting: "bye" } ]
I understand Backbone already attempts to do some merging here, but if I set the example response above, no merge happens and a new model gets added instead. I assume this is because it merges by id, and here we do not have any ids (in the local collection). In this case, greeting is my unique identifier / key.
The reason I am trying to do this is because I have a local collection and I simply want to see what already exists from that collection (using the key greeting) and merge any findings in.
My solution:
feeds.fetch({
add: false,
remove: false,
merge: false,
data: params,
success: function (feeds, response) {
// Merge any matches
_.each(response.results, function (result) {
_.each(feeds.models, function (feed) {
// We have to `parse` the result before setting it, as Model#set does
// not automatically run `parse` (Collection#set does).
result = feed.parse(result)
if (feed.get('rssUrl') === result.rssUrl) feed.set(result)
})
})
cb(feeds)
}
})
You can tell backbone to use a different key for the id attribute on your model:
GreetingModel = Backbone.Model.extend({
idAttribute: "greeting"
});
GreetingCollection = Backbone.Collection.extend({
model: GreetingModel
});
http://backbonejs.org/#Model-idAttribute
Edit: I suppose you could use two separate collections for local and server side.
var localCollection = new Backbone.Collection([ { greeting: "hi" }, { greeting: "bye" } ]);
ServerCollection = Backbone.Collection.extend({
url: "/api/"
...
});
var serverCollection = new ServerCollection({});
serverCollection.on("reset", function() {
localCollection.each(function(localModel) {
var greeting = localModel.get("greeting");
serverModel = serverCollection.findWhere({greeting: greeting});
if(serverModel) {
localModel.set(serverModel.attributes);
}
});
});
serverCollection.fetch();

Resources