How to iterate over multiple arrays without nested observables - system.reactive

I must iterate over array, find correspondent objects in other array an merge the result in a object.
Assume I have three arrays
var users = [
{ name: "A", type: 2, level: 1 },
{ name: "B", type: 1, level: 2 }
]
var types = [
{ description: "Type 1", id: 1 },
{ description: "Type 2", id: 2 }
]
var levels = [
{ description: "Level 1", id: 1 },
{ description: "Level 2", id: 1 }
]
I want to have following result:
var users = [
{ name: "A", type: 2, level: 1, levelDescription: "Level 1", typeDescription: "Type 2" },
{ name: "B", type: 1, level: 2, levelDescription: "Level 2", typeDescription: "Type 1" }
]
I know I can achieve it like that
var usersObservable = RX.Observable.fromArray(users);
var typesObservable = Rx.Observable.fromArray(types);
var levelsOBservable = Rx.Observable.fromArray(levels);
var uiUsers= [];// not really needed because I will use the same users array again.
usersObservable.map(function(user) {
typesObservable.filter(function(type) {
return type.id == user.type;
}).subscribeOnNext(function(userType) {
user.typeDescription = userType.description;
});
return user;
}).map(function(user) {
levelsOBservable.filter(function(level) {
return level.id == user.levelId;
}).subscribeOnNext(function(level) {
user.levelDescription = level.description;
});
return user;
})
.subscribeOnNext(function(user) {
uiUsers.push(user);
})
I would like to have a solution without nested Observables.
Thanks.

I am not sure why you are using Rx at all for this problem. You have data in space (i.e. arrays), not data over time (i.e. an observable sequence). But you force these arrays into Rx to then create a very complicated solution.
I think you are looking for something like the answer here https://stackoverflow.com/a/17500836/393615 where you would join the source array types. In your case you just "inner-join" twice to combine all three data sets.

You can archive this by using the switchMap operator that combines the result of a filtered stream with the latest value of the original stream and uses a projection function to merge the results into a single object. This can be generalised in your example such that you can use a generic higher order function in both cases. See fiddle.
Full code (ES2015, RxJS5):
const users = [
{ name: "A", type: 2, level: 1 },
{ name: "B", type: 1, level: 2 }
];
const types = [
{ description: "Type 1", id: 1 },
{ description: "Type 2", id: 2 }
];
const levels = [
{ description: "Level 1", id: 1 },
{ description: "Level 2", id: 2 }
];
const users$ = Rx.Observable.from(users);
const types$ = Rx.Observable.from(types);
const levels$ = Rx.Observable.from(levels);
function join(s$, sourceProperty, targetProperty, streamProperty) {
return function(initObj) {
const stream$ = s$.filter(x => x.id === initObj[sourceProperty]);
return Rx.Observable.combineLatest(
Rx.Observable.of(initObj),
stream$,
(obj, streamObj) => {
const prop = streamObj[streamProperty];
return Object.assign({}, obj, { [targetProperty]: prop });
}
);
};
}
users$
.switchMap(join(types$, 'type', 'typeDescription', 'description'))
.switchMap(join(levels$, 'level', 'levelDescription', 'description'))
.subscribe(x => console.log(x));

Related

Merge or 'reference' and object into another through GraphQL?

Very new to graphQL (and MongoDB), and I am wondering how to reference an another object in graph QL.
I have two objects in two collections in MongoDB...
{
_id: 1,
companies: [
{
id: 1,
name: 'Google'
},
{
id: 2,
name: 'Apple'
}
]
}
{
_id: 2,
jobs: [
{
id: 1,
title: 'Designer'
},
{
id: 2,
name: 'Developer'
}
]
}
The Designer job is posted by google, and I want to include that in the returned object from GraphQL (I am using the 'id: 1' as a reference I guess? Presume ObjectID might be the way to go instead tho )
How would I go about that?
Ideally I want to return
{
"data": {
"job": {
"id": 1,
"title": "Designer",
"company": {
id: 1,
name: "Google"
}
}
}
}
But not sure how to go about it, I currently have...
resolvers.js
export const resolvers = {
Query: {
jobs: async (_parent, {}, context) => {
const jobs = await context.db
.collection('jobs')
.findOne()
return jobs.jobs
},
companies: async (_parent, {}, context) => {
const companies = await context.db
.collection('companies')
.findOne()
return companies.companies
},
job: async (_parent, { id }, context) => {
const job = await context.db.collection('jobs').findOne()
return job.jobs.find((job) => job.id === Number(id))
},
},
}
typeDefs.js
export const typeDefs = gql`
type Job {
_id: ID
id: Int
title: String
}
type Company {
_id: ID
id: Int
name: String
}
type Query {
jobs: [Job]
companies: [Company]
job(id: Int): Job
}
`
But not sure how to tie these in together? I am using Apollo / GraphQL / MongoDB / NextJS and essentially set up very close to this
Thanks in advance for any help or guidance!

Traverse through an Array to obtain nested object

I am trying to traverse through my array to get a specific object nested inside of it.
Some objects contain a children property, which should be traversed until a matching object is found.
Here's some example data, I am trying to obtain the object with id as 4
const items = [{
id: 1,
title: 'Title for Item 1'
},
{
id: 2,
title: 'Title for Item 2',
children: [
{
id: 3,
title: "Title for Item 3",
children: [
{
id: 4,
title: "Title for Item 4",
}
]
}
]
},
]
I've written some traversal code but it returns undefined.
const items = [{
id: 1,
title: 'Title for Item 1'
},
{
id: 2,
title: 'Title for Item 2',
children: [
{
id: 3,
title: "Title for Item 3",
children: [
{
id: 4,
title: "Title for Item 4",
}
]
}
]
},
]
const getItem = (items) => {
if (!items) return;
const item = items && items.find(i => i.id === 4);
if (!item) {
items.forEach(i => {
return getItem(i.children)
})
// This is where undefined is returned
} else {
console.log({
item
}) // Prints the correct object.
return item;
}
};
const s = getItem(items); // undefined
document.querySelector('#foo').textContent = s ? s : 'undefined';
<div id="foo"></div>
At least two issues explain why it does not work:
A return statement in a forEach callback will return the returned value to nowhere. Nothing happens with it.
The result of the recursive call is not checked. It needs to be checked to see if it is defined. Depending on that you can decide whether to continue the loop or exit from it.
Replace that forEach with a for...of loop so you can return "out of it", but only do that when you have a match, otherwise you need to continue the loop:
for (const item of items) {
const match = getItem(item.children);
if (match) return match;
}
Note that in your snippet you should not set the textContent to the return value, as that is an object and will get converted to the string "[Object object]". You could for instance just grab the title string and put that in textContent:
const items = [{
id: 1,
title: 'Title for Item 1'
},
{
id: 2,
title: 'Title for Item 2',
children: [
{
id: 3,
title: "Title for Item 3",
children: [
{
id: 4,
title: "Title for Item 4",
}
]
}
]
},
]
const getItem = (items) => {
if (!items) return;
const item = items && items.find(i => i.id === 4);
if (!item) {
for (const item of items) {
const match = getItem(item.children);
if (match) return match;
}
} else {
console.log({
item
}) // Prints the correct object.
return item;
}
};
const s = getItem(items); // undefined
document.querySelector('#foo').textContent = s ? s.title : 'undefined';
<div id="foo"></div>

Correct way to return from mongo to datatable

I'm using mongoose and returning documents from a collection to be displayed using datatables. I'm having some issues though. The client-side code is
var table = $('#dataTables-example').DataTable( {
"bProcessing" : true,
"bServerSide" : true,
"ajax" : {
"url" : "/mongo/get/datatable",
"dataSrc": ""
},
"columnDefs": [
{
"data": null,
"defaultContent": "<button id='removeProduct'>Remove</button>",
"targets": -1
}
],
"aoColumns" : [
{ "mData" : "name" },
{ "mData" : "price" },
{ "mData" : "category" },
{ "mData" : "description" },
{ "mData" : "image" },
{ "mData" : "promoted" },
{ "mData" : null}
]
});
Then this handled on the server-side using the following
db.once('open', function callback ()
{
debug('Connection has successfully opened');
productSchema = mongoose.Schema({
name: String,
price: String,
category: String,
description: String,
image: String,
promoted: Boolean
});
Product = mongoose.model('Product', productSchema, 'products');
});
exports.getDataForDataTable = function (request, response) {
Product.dataTable(request.query, function (err, data) {
debug(data);
response.send(data);
});
};
If I use the above code the datatable fails to display the documents, claiming no matching records found BUT it does correctly display the number of docs Showing 1 to 2 of 2 entries. If I change the server side code to response with data.data instead of data, the documents are correctly populated in the table BUT the number of records is no longer found, instead saying Showing 0 to 0 of 0 entries (filtered from NaN total entries)
exports.getDataForDataTable = function (request, response) {
Product.dataTable(request.query, function (err, data) {
debug(data);
response.send(data.data);
});
The actual data being returned when querying mongo is
{ draw: '1', recordsTotal: 2, recordsFiltered: 2, data: [ { _id: 5515274643e0bf403be58fd1, name: 'camera', price: '2500', category: 'electronics', description: 'lovely', image: 'some image', promoted: true }, { _id: 551541c2e710d65547c6db15, name: 'computer', price: '10000', category: 'electronics', description: 'nice', image: 'iamge', promoted: true } ] }
The third parameter in mongoose.model sets the collection name which is pluralized and lowercased automatically so it has no effect in this case.
Assuming your Product variable has been declared early on and global, try this:
products = mongoose.model('products', productSchema);
Product = require('mongoose').model('products');
Did you try to remove the dataSrc field in the DataTable configuration:
"ajax" : {
"url" : "/mongo/get/datatable",
},

Why does the Kendo Grid show false in all records of my grid, even when some have true?

I have put together a simple jsfiddle demonstrating the issue. It has a grid with two records. One has a true value in in the Boolean column and the other has a false.
I have logged the data to the console so you can see the values that the grid is getting.
Yet the grid shows false for both rows.
http://jsfiddle.net/codeowl/KhBMT/
Thanks for your time,
Scott
Code for StackOverflow:
var _Data = [
{ "SL_TestData_ID": "1", "SL_TestData_String": "Bool is 1", "SL_TestData_Boolean": "1" },
{ "SL_TestData_ID": "2", "SL_TestData_String": "Bool is 0", "SL_TestData_Boolean": "0" }
];
var _kendoDataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
console.log('Transport READ Event Raised - Data: ', JSON.stringify(_Data, null, 4));
options.success(_Data);
}
},
schema: {
model: {
id: "SL_TestData_ID",
fields: {
SL_TestData_ID: { editable: false, nullable: false },
SL_TestData_String: { type: "string" },
SL_TestData_Boolean: { type: "boolean" }
}
}
},
error: function (a) {
$('#TestGrid').data("kendoGrid").cancelChanges();
}
});
// Initialize Grid
$("#TestGrid").kendoGrid({
columns: [
{ field: "SL_TestData_ID", title: "ID" },
{ field: "SL_TestData_String", title: "String" },
{ field: "SL_TestData_Boolean", title: "Boolean" }
],
dataSource: _kendoDataSource
});
I found that if I altered my select statement to return "TRUE"/"FALSE" for my TINYINT column in the database it worked. Eg;
SELECT
SL_TestData_ID,
SL_TestData_Number,
SL_TestData_String,
SL_TestData_Date,
SL_TestData_DateTime,
if (SL_TestData_Boolean = 1, "TRUE", "FALSE") as SL_TestData_Boolean
FROM
SL_TestData;
Regards,
Scott

Kendo DataSource: How to define "Computed" Properties for data read from remote odata source

Situation:
kendo DataSource
var ordersDataSource = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
url: "http://localhost/odata.svc/Orders?$expand=OrderDetails"
}
},
schema: {
type: "json",
data: function(response){
return response.value;
}
total: function(response){
return response['odata.count'];
}
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
})
the json data read from the odata source is like:
{
odata.metadata: "xxxx",
odata.count: "5",
value: [
{
OrderId: 1,
OrderedDate: "2013-02-20",
OrderInfoA: "Info A",
OrderInfoB: "Info B"
OrderDetails: [
{
OrderDetailId: 6,
OrderDetailInfoC: "Info C",
OrderDetailInfoD: "Info D"
},
{
//Another OrderDetail's data
}
]
},
{
// Another Order's data
}
]
}
Question 1:
1.If I wanna define a "computed" property: OrderedDateRelative, which should be the number of days between Today(2013-02-25) and the Day the Order was Created(2013-02-20), Like: "5 days ago", HOW can i achieve this in the client side?
Answer to Question1: http://jsbin.com/ojomul/7/edit
Question 2 --UPDATE--
2.Every Order has its Nested Property OrderDetails, so is it possible to define a Calculated Field for the Nested OrderDetails Property? Like: OrderDetailInfoCAndD for each OrderDetail, and the value should be something like: OrderDetailInfoC + OrderDetailInfoD, which is "Info C Info D"?
Thanks,
dean
You can create a calculated field by specifying the model of the data source:
dataSource = new kendo.data.DataSource({
data: [
{ first: "John", last: "Doe" },
{ first: "Jane", last: "Doe" }
],
schema: {
model: {
// Calculated field
fullName: function() {
return this.get("first") + " " + this.get("last");
}
}
}
});
Here is a live demo: http://jsbin.com/ojomul/1/edit
Here is a way to use calculated field in Kendo Grid.
var crudServiceBaseUrl = "http://demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
}
},
pageSize: 20,
schema: {
model: {
total: function (item) {
return this.UnitPrice * this.UnitsInStock;
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
sortable: true,
filterable: true,
toolbar: ["create"],
columns: [
{ field: "UnitPrice", title: "Unit Price"},
{ field: "UnitsInStock", title: "Units In Stock", width: "120px" },
{ field: "total()", title: "Total" }]
});
Below an example to use it in a grid. It can then also sort the column.
$("#grid").kendoGrid({
dataSource: {
data: [
{ first: "John", last: "Doe" },
{ first: "Jane", last: "Doe" }
],
schema: {
model: {
// Calculated field
fullName: function() {
return this.first + " " + this.last;
},
fields: {
first: { type: "string" },
last: { type: "string" }
}
}
}
},
columns: [
{
// Trigger function of the Calculated field
field: "fullName()",
title: "Fullname"
},
{
field: "first",
title: "firstname"
}
]
});