Can anyone please suggest me on how to apply sorting to dropdown list in Vue Js
I have used v-select from vuetify
`<v-select v-model='coursesList' :options="courses" :enableDropup="true" options-label="name" options-value="id" name='courseName[]'></v-select>`
mutations:{
setCourseItems (state,response){
state.courseItems=response
}
}
JSON:
[
{
"stock": "available",
"name": "Higher Engineering maths"
},
{
"stock": "available",
"name": "Qantum Physics"
},
{
"stock": "available",
"name": "Biology"
}
]
In javascript you can use the sort method to sort an array.
Here your response seems to be a json array, you can call sort() on it and give it a custom function for sorting. Example :
var myArray = [
{
stock: "available",
name: "Higher Engineering maths"
},
{
stock: "available",
name: "Qantum Physics"
},
{
stock: "available",
name: "Biology"
}
]
myArray.sort(function (item1, item2) => {
//if the result of this method is negative, item2 is considered "bigger" than item1, and vice versa
return item1.name.toLowerCase() < item2.name.toLowerCase() ? -1 : 1
})
this will sort your array by alphabetical order of the name field. Note that toLowerCase() is not necessary but it's advised in case you don't control the input and don't want to treat capital letters differently.
Related
I'm trying to get an index on a field of a child item in my document. The data is this:
[
{
"ref": Ref(Collection("ColA"), "111111111111111111"),
"ts":1659241462840000,
"data":{
"name":"Test a",
"members":[
{
"userId":"1",
"roles":[
"admin"
]
}
]
}
},
{
"ref": Ref(Collection("ColA"), "111111111111111112"),
"ts":1659241462840000,
"data":{
"name":"Test b",
"members":[
{
"userId":"1",
"roles":[
"admin"
]
},
{
"userId":"2",
"roles":[
"read-only"
]
}
]
}
},
{
"ref": Ref(Collection("ColA"), "111111111111111113"),
"ts":1659241462840000,
"data":{
"name":"Test c",
"members":[
{
"userId":"2",
"roles":[
"admin"
]
}
]
}
}
]
Trying to using data.members.userId as term in the index. This only gives back one result when I use the index with the filter value '1'
Then I tried to create the index as following:
CreateIndex({
name: 'spaces_member_ids',
source: {
collection: Collection("ColA"),
fields: {
members: Query(
Lambda(
"ColA",
Select(["data", "members", "userId"], Var("ColA"), '')
)
),
},
},
terms: [
{ binding: "members" },
],
values: [
{ field: "data.name" },
{ field: "ref" },
]
})
But that gives no results when I use the index with the filter value '1' Both times I expect to get two items back (Test a and Test b).
Anyone knows how to create an index that gived back all the data of ColA filtered on field 'userId' in the 'members' array?
The problem is that there is no userId field as a direct descendant of the members array.
For background, Fauna index entries can only contain scalar values. Objects are not indexed at all. For arrays, one index entry is created per scalar value in the array. If you attempt to index multiple array fields, the number of index entries produced is the Cartesian product of the items in all indexed arrays.
If you create your index like so:
CreateIndex({
name: 'spaces_member_ids',
source: Collection("ColA"),
terms: [
{ field: ["data", "members", 0, "userId"] },
],
values: [
{ field: ["data", "name"] },
{ field: "ref" },
]
})
Then you'll be able to search for userId values that appear in the first item in the members array.
If you need to create index entries for all userId values from each ColA document, then your binding approach is close, but it needs to provide an array.
CreateIndex({
name: "spaces_member_ids",
source: {
collection: Collection("ColA"),
fields: {
members: Query(
Lambda(
"ColA",
Map(
Select(["data", "members"], Var("ColA"), []),
Lambda(
"member",
Select(["userId"], Var("member"), "")
)
)
)
),
},
},
terms: [
{ binding: "members" },
],
values: [
{ field: ["data", "name"] },
{ field: "ref" },
]
})
The notable changes that I made are:
Within the binding, Map is used to iterate on the members field in the document.
Simply returning the userId field value within a Map is sufficient to return an array of userId values.
Corrected the syntax in the values definition. Fauna indexes don't process dot notation.
I have json data similar to this:
{
"Sections": [
{
"Categories": [
{
"Name": "Book",
"Id": 1,
"Options": [
{
"Name": "AAAA",
"OptionId": 111
},
"Selected": 0
},
{
"Name": "Car",
"Id": 2,
"Options": [
{
"Name": "BBB",
"OptionId": 222
},
"Selected": 0
},
],
"SectionName": "Main"
},
... more sections like the one above
]
}
Given this data, I want to find a category inside a section based on its (Category) Id, and set its selected option, I tried this, but couldn't get it to work....Note Category Id will be unique in the whole data set.
_.find(model.Sections, { Categories: [ { Id: catId } ]});
According to your data model, it looks like you're trying to find an element that is inside a matrix: Sections can have multiple Categories and a Category can have multiple types (car, book...).
I'm afraid there isn't a function in lodash that allows a deep find, you'll have to implement it the 'traditional' way (a couple of fors).
I provide this solution that is a bit more 'functional flavoured' than the traditional nested fors. It also takes advantage of the fact that when you explicitly return false inside a forEach, the loop finishes. Thus, once an element with the provided id is found, the loop is ended and the element returned (if it's not found, undefined is returned instead).
Hope it helps.
const findCategoryById = (sections, id) => {
var category;
_.forEach(sections, (section) => {
category = _.find(section.Categories, ['Id', id]);
return _.isUndefined(category);
});
return category;
};
const ex = {
"Sections": [{
"Categories": [{
"Name": "Book",
"Id": 1,
"Options": [{
"Name": "AAAA",
"OptionId": 111
}],
"Selected": 0
},
{
"Name": "Car",
"Id": 2,
"Options": [{
"Name": "BBB",
"OptionId": 222
}],
"Selected": 0
}
],
"SectionName": "Main"
}]
};
console.log(findCategoryById(ex.Sections, 2));
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.5/lodash.min.js"></script>
I am new to Ramda and I am trying to achieve the following:
I have an array of objects (i.e. messages).
I want to group the messages by counter party ID (either the sender or the recipient ID, whichever is not 1, see my groupBy lambda below).
I am going to obtain an object whose keys will be the counter party IDs and values an array of the messages exchanged with that counter party.
I then want to sort by date descending those arrays of messages.
And finally keep the most recent message and thus obtain an array containing the most recent message exchanged with each of the counter parties.
Because I have two counter parties above, I should have an array of two messages.
Here is what I have attempted:
const rawMessages = [
{
"sender": {
"id": 1,
"firstName": "JuliettP"
},
"recipient": {
"id": 2,
"firstName": "Julien"
},
"sendDate": "2017-01-28T19:21:15.863",
"messageRead": true,
"text": "ssssssss"
},
{
"sender": {
"id": 3,
"firstName": "Juliani"
},
"recipient": {
"id": 1,
"firstName": "JuliettP"
},
"sendDate": "2017-02-01T18:08:12.894",
"messageRead": true,
"text": "sss"
},
{
"sender": {
"id": 2,
"firstName": "Julien"
},
"recipient": {
"id": 1,
"firstName": "JuliettP"
},
"sendDate": "2017-02-07T22:19:51.649",
"messageRead": true,
"text": "I love redux!!"
},
{
"sender": {
"id": 1,
"firstName": "JuliettP"
},
"recipient": {
"id": 3,
"firstName": "Juliani"
},
"sendDate": "2017-03-13T20:57:52.253",
"messageRead": false,
"text": "hello Juliani"
},
{
"sender": {
"id": 1,
"firstName": "JuliettP"
},
"recipient": {
"id": 3,
"firstName": "Juliani"
},
"sendDate": "2017-03-13T20:56:52.253",
"messageRead": false,
"text": "hello Julianito"
}
];
const currentUserId = 1;
const groupBy = (m: Message) => m.sender.id !== currentUserId ? m.sender.id : m.recipient.id;
const byDate = R.descend(R.prop('sendDate'));
const sort = (value, key) => R.sort(byDate, value);
const composition = R.compose(R.map, R.head, sort, R.groupBy(groupBy));
const latestByCounterParty = composition(rawMessages);
console.log(latestByCounterParty);
Here is the corresponding codepen:
https://codepen.io/balteo/pen/JWOWRb
Can someone please help?
edit: Here is a link to the uncurried version: here. The behavior is identical without the currying. See my comment below with my question as to the necessity of currying.
While I think the solution from Scott Christopher is fine, there are two more steps that I might take with it myself.
Noting that one of the important rules about map is that
map(compose(f, g)) ≍ compose(map(f), map(g))
when we're already inside a composition pipeline, we can choose to unnest this step:
R.map(R.compose(R.head, R.sort(R.descend(R.prop('sendDate'))))),
and turn the overall solution into
const currentMessagesForId = R.curry((id, msgs) =>
R.compose(
R.values,
R.map(R.head),
R.map(R.sort(R.descend(R.prop('sendDate')))),
R.groupBy(m => m.sender.id !== id ? m.sender.id : m.recipient.id)
)(msgs)
)
Doing this, is, of course, a matter of taste. But I find it cleaner. The next step is also a matter of taste. I choose to use compose for things that can be listed on a single line, and hence make some obvious connection between the formats compose(f, g, h)(x) and f(g(h(x))). If it spans multiple lines, I prefer to use pipe, which behaves the same way, but runs it's functions from first to last. So I would change this a bit further to look like this:
const currentMessagesForId = R.curry((id, msgs) =>
R.pipe(
R.groupBy(m => m.sender.id !== id ? m.sender.id : m.recipient.id),
R.map(R.sort(R.descend(R.prop('sendDate')))),
R.map(R.head),
R.values
)(msgs)
)
I find this top-down reading easier than the bottom up needed with longer compose versions.
But, as I said, these are matters of taste.
You can see these examples on the Ramda REPL.
Your example was close to what you wanted, though you need just needed to move the composition of head and sort to the function argument given to map and then call values on the final result to convert the object to an array of values.
const currentMessagesForId = R.curry((id, msgs) =>
R.compose(
R.values,
R.map(R.compose(R.head, R.sort(R.descend(R.prop('sendDate'))))),
R.groupBy(m => m.sender.id !== id ? m.sender.id : m.recipient.id)
)(msgs))
currentMessagesForId(currentUserId, rawMessages)
I've posed a question about Bootstrap Tables but meanwhile I moved to Datatables as I was feeling blocked. My problem, however, is the same.
None of the two can easily handle nested JSON results. For instance if I choose "field: author", it processes the following as "[Object Object], [Object Object]".
"author": [
{
"family": "Obama",
"given": "Barack"
},
{
"family": "Obama",
"given": "Michelle"
}
I can select the results individually, say "field: author[, ].family", which returns a list like "Obama, Obama". But I want an output like "given+family1, given+family2, ..".
You can use custom rendering. DataTables allows you to define custom rendering for each column.
Here is a sample that I worked out. I am doing custom rendering for Author column.
$(document).ready(function() {
var dataSet = [
{ "name": "How to DataTables", "author": [{ "firstname": "jack", lastname: "d" }, { "firstname": "dick", lastname: "j" }] },
{ "name": "How to Custom Render", "author": [{ "firstname": "bill", lastname: "g" }, { "firstname": "scott", lastname: "g" }] }
];
$('#example').DataTable({
data: dataSet,
columns: [
{ title:"Book Name",
data: "name" },
{
title: "Authors",
data: "author",
render: function(data, type, row) {
//return data.length;
var txt = '';
data.forEach(function(item) {
if (txt.length > 0) {
txt += ', '
}
txt += item.firstname + ' ' + item.lastname;
});
return txt;
}
}
]
});
});
I'm using v4.11.0.
I would like sort objects based on milliseconds property.
Here's the array :
[
{
"name": "bug12755.xml",
"list": "bugs42",
"start-date": "2015-09-14",
"age": {
"text": "7 months",
"milliseconds": 18381227304
}
},
{
"name": "bug12922.xml",
"list": "bugs42",
"start-date": "2015-08-27",
"age": {
"text": "8 months",
"milliseconds": 19936427304
}
},
{
"name": "bug13183.xml",
"list": "bugs50",
"start-date": "2015-08-27",
"age": {
"text": "8 months",
"milliseconds": 19936427305
}
}
]
I'm missing something fundamental about the iteratee function. I have this but does not seem to sort the array. Thanks in advance!
_.orderBy(list, function(item) {
return item.age.value;
}, ['desc']);
It seems that you are ordering by the wrong property value.
_.orderBy(list, item => item.age.milliseconds, ['desc']);
https://codepen.io/a2qube/pen/pKYrgN
A simple example on how you can use the Lodash: orderBy to sort based on inner attributes.
hotels = _.orderBy(hotels, 'account.id', 'desc');
A simple example on how you can sort by another property if one is undefined:
import _ from "lodash";
const orderItems = (items) => _.orderBy(items, (item) => item.displayName || item.name, ["asc"]);
Referance:
https://stackoverflow.com/a/36606220/5994546
lodash orderBy on nested property