create array for morris js in laravel - arrays

I have difficulty loading certain data from the table to get a json array and include it into the morris js donut (example: https://codepen.io/ncarlucci/pen/JYxQBK)
I want to load from the table subscriber the different names from the column type and count them to get the following array:
[
{value: 50, label: 'typename1'},
{value: 25, label: 'typename2'},
{value: 25, label: 'typename3'},
],
if I do it like this:
$subscriber = Subscribe::select('type')->get()->groupBy('type')
->map(function($subscribe){
return $subscribe->count();
})->toJson();
I get the follow output, but it is false:
{"company":1,"person":16,"user":6}

There might be a nicer way to handle your case, but since you didn't provide more informations about your model or database structure, this should work:
$subscriber = Subscribe::select('type')->get()
->groupBy('type')
->map(function($subscribe, $label) {
return ['value' => $subscribe->count(), 'label' => $label];
})
->values()
->toJson();
The key is to build the inner array element within the map function, then call values() to get rid of the unneded outer label left by the map function.
If you need further explaination, just ask in the comments below

Related

Typescript array - need to remove all nested arrays that do not have defaultBranch: object

I am using the Azure DevOps Extension api to create an array of all of my repositories in ADO. This results in an array with several nested arrays.
Some of these nested arrays do not have a defaultBranch object because the repositories are empty. I would like to remove any nested arrays that are missing the defaultBranch object.
Example of current array:
repos = [{id: 123, defaultBranch: 'master', name: repo1},
{id: 234, name: repo2},
{id: 345, defaultBranch: 'master', name: repo3}]
I would like to remove that middle array and any others that are missing the defaultBranch, leaving me with the below array:
repos = [{id: 123, defaultBranch: 'master', name: repo1},
{id: 345, defaultBranch: 'master', name: repo3}]
I am not sure if it would be easier to remove any nested arrays that do not meet the requirements or to create a new array that leaves them out. I am newer to Typescript/coding so I am not sure where to begin.
I appreciate any help!
array's filter should sort you out
let filteredRepos = repos.filter(r => Boolean(r.defaultBranch))
When the defaultBranch is non-existant, it is a "falsy" value, which means it will be discarded from the newly created array.

How can I remove items from a JSON array based on a list of array keys?

I'm trying to build an API in node.js that syncs two different systems, and I'm having trouble breaking down an array of objects I receive from my source system.
Basically, I receive an array that looks a bit like this:
sourcedata = {
"items": [
{ "id": "item1",
"some fields": {...array of some fields },
"more fields": {another block of fields}
},
{ "id": "item2",
"some fields": {...array of some fields },
"more fields": {another block of fields}
}]
}
What I also have are three arrays of IDs - new ones (means I have to send them to the target system), old ones (to delete from the target), and ones that appear on both - those I need to check a special tag to see if they are different or not.
e.g.
newitems = [id1,id2,id3]
existingItems [id4,id5,id6]
deletedItems = [id7,id8]
What I'm trying to do is create new arrays that will only contain the data of the NEW and EXISTING items, so I can process and send them over to the target system without scanning the sourcedata array for each key and deciding what to do . I know how to do that when I compare simple arrays, but here I need the entire objects and all its fields copied over, and I can't
find the proper way to do it. Any help would be appreciated.
You can make use of the filter function. It filters out elements of array based on your condition. You may use it with the includes function to determine if a thing is in an array. For example:
sourceArray = [
{
id: 'a'
},
{
id: 'b'
},
{
id: 'c'
},
{
id: 'd'
}
]
var toDelete = ['c', 'b']
sourceArray = sourceArray.filter(x => !toDelete.includes(x.id))
// some items in sourceArray have now been removed.
Note that filter and includes may require a recent version of nodejs.

How to generate the right data structure for ngoptions in single request

I'm trying to return a data structure for an Angular screen with several dropdowns.
I don't want to make multiple requests to get the options for each select so I was hoping to create a single nested data structure in Django that contains all the options for each select (there are only a small number)
Angular wants something like this to use with the select and ngoptions directives:
{'booking_name': 'acme',
'current_sales_person': 2,
'sales_people_options': [
{id: 1, name: 'rod'},
{id: 2, name: 'jane'},
{id: 3, name: 'freddy'}
],
... lots more fields here ...
}
sales_people_options would populate the options for the dropdown and current_sales_person indicates which salesperson is initially selected.
How can I get Django Rest Framework to return this in a single request from a ModelSerializer?
I could just create the JSON directly via JSONRenderer but I've got a lot of other fields so I'm keen to use ModelSerializer.
The only way seems to be to add a method called sales_people_options to my Model.
However - I've got several of these fields to generate and it seems very wrong to add model methods for something that I only need for one specific serializer.
EDIT - I think I might need to subclass serializer.Field and override a method (probably field_to_native).
This is just a json object. The Django rest framework is capable of returning json strings which you can then JSON.stringify the string returned to turn it into an object angular is expecting.
{'booking_name': 'acme',
'current_sales_person': 2,
'sales_people_options': [
{id: 1, name: 'rod'},
{id: 2, name: 'jane'},
{id: 3, name: 'freddy'}
Checkout the Django JSON renderer; http://www.django-rest-framework.org/api-guide/renderers
This might be a weird way to do it but it worked:
class BookingSerializer(serializers.ModelSerializer):
class UserOptionsField(serializers.Field):
def field_to_native(self, obj, field_name):
return User.objects.all().values('id', 'username')
sales_people_options = UserOptionsField()
class Meta:
model = Booking
fields = (
'id', 'booking_no', 'current_salesperson', 'sales_people_options',
)
EDIT: And here's a generic solution:
class ModelOptionsField(serializers.Field):
def __init__(self, source=None, label=None, help_text=None, queryset=None, fields=None):
self.queryset = queryset
self.fields = fields
super(ModelOptionsField, self).__init__(source, label, help_text)
def field_to_native(self, obj, field_name):
return self.queryset.values(*self.fields)
that you use like this:
class MySerializer(serializers.ModelSerializer):
my_options_list = ModelOptionsField(queryset=User.objects.all(), fields=('id', 'username'))

ngOptions From Simple Key-Value Object

There are other answers that deal with using ng-option with an object formatted like so:
$scope.opts = [
{value: 111, text: '1st' },
{value: 222, text: '2nd' }
];
My question is, can it be done with an object formatted like this?
$scope.opts = [
{'111': '1st'},
{'222': '2nd'}
];
Trying it out doesn't work for me.
Any help?
To clarify:
I'd like the options to be like this <option value="111">1st</option, etc, where the browser shows 1st, and the model returns 111. Can this be done with an array of simplified objects?
No, the answer you point out does not say the same thing as you case. You have an array of objects having a single property with different names; the name of the single property is the key, the value is tha value.
The "object" syntax for the select is about an object, i.e. in your case it should be:
$scope.opts = {
'111': '1st',
'222': '2nd'
};
What you lose with this? No guaranteed iteration order.

MongoDB: Query and retrieve objects inside embedded array?

Let's say I have the following document schema in a collection called 'users':
{
name: 'John',
items: [ {}, {}, {}, ... ]
}
The 'items' array contains objects in the following format:
{
item_id: "1234",
name: "some item"
}
Each user can have multiple items embedded in the 'items' array.
Now, I want to be able to fetch an item by an item_id for a given user.
For example, I want to get the item with id "1234" that belong to the user with name "John".
Can I do this with mongoDB? I'd like to utilize its powerful array indexing, but I'm not sure if you can run queries on embedded arrays and return objects from the array instead of the document that contains it.
I know I can fetch users that have a certain item using {users.items.item_id: "1234"}. But I want to fetch the actual item from the array, not the user.
Alternatively, is there maybe a better way to organize this data so that I can easily get what I want? I'm still fairly new to mongodb.
Thanks for any help or advice you can provide.
The question is old, but the response has changed since the time. With MongoDB >= 2.2, you can do :
db.users.find( { name: "John"}, { items: { $elemMatch: { item_id: "1234" } } })
You will have :
{
name: "John",
items:
[
{
item_id: "1234",
name: "some item"
}
]
}
See Documentation of $elemMatch
There are a couple of things to note about this:
1) I find that the hardest thing for folks learning MongoDB is UN-learning the relational thinking that they're used to. Your data model looks to be the right one.
2) Normally, what you do with MongoDB is return the entire document into the client program, and then search for the portion of the document that you want on the client side using your client programming language.
In your example, you'd fetch the entire 'user' document and then iterate through the 'items[]' array on the client side.
3) If you want to return just the 'items[]' array, you can do so by using the 'Field Selection' syntax. See http://www.mongodb.org/display/DOCS/Querying#Querying-FieldSelection for details. Unfortunately, it will return the entire 'items[]' array, and not just one element of the array.
4) There is an existing Jira ticket to add this functionality: it is https://jira.mongodb.org/browse/SERVER-828 SERVER-828. It looks like it's been added to the latest 2.1 (development) branch: that means it will be available for production use when release 2.2 ships.
If this is an embedded array, then you can't retrieve its elements directly. The retrieved document will have form of a user (root document), although not all fields may be filled (depending on your query).
If you want to retrieve just that element, then you have to store it as a separate document in a separate collection. It will have one additional field, user_id (can be part of _id). Then it's trivial to do what you want.
A sample document might look like this:
{
_id: {user_id: ObjectId, item_id: "1234"},
name: "some item"
}
Note that this structure ensures uniqueness of item_id per user (I'm not sure you want this or not).

Resources