Output is "[object Object],[object Object],..." when console logging sorted array - sorting

I'm trying to sort json response data by "id" and print the result to the console. However, I am not getting the expected result.
JSON response data (cspaces):
[
{
id: 21,
attributes: {
title: 'Office Room For Rent in Dharapuram',
image: [Object],
amenities: []
}
},
{
id: 14,
attributes: {
title: 'Shop For Rent in Ulagapuram',
image: [Object],
amenities: [Array]
}
},
{
id: 16,
attributes: {
title: 'Shop For Rent in Dharapuram',
image: [Object],
amenities: []
}
},
....
}
]
The sort function is as follows:
const sortData = type => {
const types = {
id: 'id',
};
const sortProperty = types['id'];
if (type==="latest")
{
sorted = [...cspaces].sort((a, b) => a[sortProperty]- b[sortProperty]);
filteredList = sorted.toString();
console.log("Sorted -> "+ sorted)
}
else if(type==='oldest')
{
// console.log("type -> "+ type)
sorted = [...cspaces].sort((a, b) => b[sortProperty] - a[sortProperty]);
filteredList = sorted.toString()
console.log("Sorted -> "+sorted)
}
}
The output I see in the console is [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What am I doing wrong here?

Related

model.hasMany called with something that's not a subclass of Sequelize.Model

I am getting the below error whenever I tried to call any call from serverless framework lambda
[offline] _____ HANDLER RESOLVED _____
offline: Failure: product.hasMany called with something that's not a subclass of Sequelize.Model
Error: product.hasMany called with something that's not a subclass of Sequelize.Model
at Function.hasMany (C:\Users\Kiran\Documents\Projects\Rentals-Backend\node_modules\sequelize\lib\associations\mixin.js:18:13)
at Function.Product.associate (C:\Users\Kiran\Documents\Projects\Rentals-Backend\entity\product.js:21:17)
IMPORTANT
Below code is the answer for the above error. You might missed any steps. So you can refer and fix. Thanks Anatoly who helped me to solve the problem.
Product model:
const { STRING, BOOLEAN, INTEGER } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
const Product = sequelize.define("product", {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
name: { type: STRING },
description: { type: STRING, allowNull: true },
purchase_price: { type: STRING },
tax: { type: STRING },
sale_price: { type: STRING },
categoryId: { type: STRING },
status: { type: BOOLEAN, defaultValue: 0 },
created_on: { type: INTEGER, allowNull: true },
updated_on: { type: INTEGER, allowNull: true },
}, {
timestamps: false,
freezeTableName: true,
})
Product.associate = function (models) {
Product.hasMany(models.product_image, { as: "images" });
Product.belongsTo(models.product_category, { as: "category", foreignKey: 'categoryId' });
};
return Product;
}
Image model:
const { STRING, BOOLEAN, INTEGER } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
const ProductImage = sequelize.define("product_image", {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
productId: { type: INTEGER },
fileName: { type: STRING },
url: { type: STRING },
position: { type: INTEGER },
isDefault: { type: BOOLEAN, defaultValue: 0 },
shopId: { type: STRING },
status: { type: BOOLEAN, defaultValue: 0 },
created_on: { type: INTEGER, allowNull: true },
updated_on: { type: INTEGER, allowNull: true },
}, {
timestamps: false,
freezeTableName: true,
})
return ProductImage;
}
Category model:
const { STRING, BOOLEAN, INTEGER } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
const ProductCategory = sequelize.define("product_category", {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
name: { type: STRING },
description: { type: STRING, allowNull: true },
status: { type: BOOLEAN, defaultValue: 0 },
created_on: { type: INTEGER, allowNull: true },
updated_on: { type: INTEGER, allowNull: true },
}, {
timestamps: false,
freezeTableName: true,
});
return ProductCategory;
}
This is the config file where we initialize sequelize
Config file
const Sequelize = require('sequelize')
const fs = require('fs')
const path = require('path')
const db = {}
const models = path.join(__dirname, '..', 'entity')
var basename = path.basename(module.filename)
const sequelize = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
dialect: 'mysql',
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: false
}
)
fs
.readdirSync(models)
.filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js')
})
.forEach(function (file) {
var model = require(path.join(models, file))(
sequelize,
Sequelize.DataTypes
);
db[model.name] = model;
})
Object.keys(db).forEach(function (modelName) {
if (db[modelName].associate) {
db[modelName].associate(db)
}
})
db.Sequelize = Sequelize
db.sequelize = sequelize
module.exports = db
Here we are calling product details.
Calling function
const db = require('../config/sequelize-config');
exports.getProductById = (query, username, shopId) => {
return new Promise((resolve, reject) => {
db.product.findOne({
where: {
id: query.id
},
attributes: ['id', 'name', 'description', ['purchase_price', 'purchasePrice'], 'tax', ['sale_price', 'salePrice']],
include: [{
model: db.product_image,
as: 'images',
where: {
status: 1
},
required: false,
attributes: ['id', 'fileName', 'position', 'url']
},
{
model: db.product_category,
as: 'category',
required: false,
attributes: ['id', 'name']
}]
}).then(product => {
if (product) {
resolve({ [KEY_STATUS]: 1, [KEY_MESSAGE]: "Product details fetched successfully", [KEY_DATA]: product });
} else {
reject({ [KEY_STATUS]: 0, [KEY_MESSAGE]: "Product details fetch failed" });
}
}).catch(error => {
reject({ [KEY_STATUS]: 0, [KEY_MESSAGE]: "Product details fetch failed", [KEY_ERROR]: error.message });
});
})
}
To avoid cross-reference errors and similar ones I recommend converting model definitions to functions and registering models and associations in the same one module, see this answer and the question

BotFramework - handleTeamsTaskModuleFetch URL not working

Below is the continue task module I am returning. The URL works fine when I hit it directly in the browser, but in teams, I always get this:
Task module reponse
handleTeamsTaskModuleFetch() {
return {
task: {
type: "continue",
value: {
title: "response",
url: `${process.env.HostName}/help.html`,
fallbackUrl: `${process.env.HostName}/help.html`,
width: 500,
height: 500
}
}
};
}
Can anyone see what I am doing wrong?
Cheers
Note: This is how I am creating the Adaptive Card
const adaptiveCard = {
$schema: 'http://adaptivecards.io/schemas/adaptive-card.json',
version: '1.0',
type: 'AdaptiveCard',
body: [{
type: 'TextBlock',
text: 'Task Module Invocation from Adaptive Card',
weight: 'bolder',
size: 3
}],
actions: [{
type: 'Action.Submit',
title: "TEST",
data: { msteams: { type: 'task/fetch'}, data: "meTask" }
}]
}
The URL's domain must be in the app's validDomains array in your app's manifest.

highcharts line graph with ajax

I would like to implement a simple line graph with ajax in which only two points
x will be the hours and y will be the count of calls.
CODE :
<script>
function getData() {
$.ajax({
type:'POST',
url: "http://localhost/demo_chart/test.php",
dataType: 'JSON',
success: function(response_data) {
new_data = $.map(response_data, function(i){
return {x: i['date'],y: i['count']};
});
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Count vs. Time'
},
xAxis: {
title: {
text: 'Time'
},
type: 'Time',
},
yAxis: {
title: {
text: 'Count'
}
},
series: [{
name: 'Test',
data: new_data
}]
});
}
})
}
$(document).ready(function () {
getData();
})
</script>
Output of http://localhost/demo_chart/test.php is same as below :
{"date":["13:00:00","13:00:01","13:00:02","13:00:03","13:00:04"],"count":["1","2","3","4","2"]}
But still graph is not generating. So i would like to know what is the problem here.
Anyone like to share some hint which can resolve this problem ?
Expected output is :
X- axis : show all date
Y-axis : show count
You need to correct your mapping function, for example:
var response = {
"date": ["13:00:00", "13:00:01", "13:00:02", "13:00:03", "13:00:04"],
"count": ["1", "2", "3", "4", "2"]
};
new_data = $.map(response.date, function(el, index) {
return {
name: el,
y: parseInt(response['count'][index])
};
});
Additionally, with that data structure, I recommend you to use category axis type.
xAxis: {
...,
type: 'category'
}
Live demo: http://jsfiddle.net/BlackLabel/ptx6fy2q/
API Reference: https://api.highcharts.com/highcharts/xAxis.type

How can I get graphql to output this list of object for the client?

I have a graphql server, and I am trying to implement a query that will update the client with a list of nodes.
In nodes.js I have:
export const nodes = {
"nodes": [
{id: 1, "name": 'building_1', "hasStrobe": true},
{id: 2, "name": 'building_2', "hasStrobe": false},
{id: 3, "name": 'building_3', "hasStrobe": true}
]
}
My query in schema.js is as follows:
const Query = new GraphQLObjectType({
name: 'Query',
description: 'Root query object',
fields() {
return {
message: {
type: Message,
resolve() {
return getMessage();
},
},
system: {
type: System,
resolve() {
return getSystemInfo();
},
},
nodes: {
type: Nodes,
resolve() {
//console.log(nodes.nodes)
return nodes.nodes;
}
},
// alert: {
// type: Alert,
// resolve() {
// return 'poke';
// }
// }
};
},
});
And my Nodes type is as follows:
const Nodes = new GraphQLObjectType({
name: 'Nodes',
description: 'List of zone nodes and their capabilities.',
fields() {
return {
nodes: {
type: GraphQLString,
resolve(msg) {
console.log(msg)
return msg;
}
},
}
}
});
When the query is run, it logs nodes.nodes correctly to the console:
[ { id: 1, name: 'building_1', hasStrobe: true },
{ id: 2, name: 'building_2', hasStrobe: false },
{ id: 3, name: 'building_3', hasStrobe: true } ]
While the query output is:
{
"data": {
"system": {
"uname": "4.11.5-2-ck-haswell\n",
"time": "Thu Jun 22 2017 17:39:29 GMT-0500 (CDT)"
},
"nodes": {
"nodes": "[object Object],[object Object],[object Object]"
}
}
}
I'm unsure of how to process the data array in a way that will work to output the nodes.

How to allow kendo grid to bind to an undefined field

I have this json object
{
id: string,
name: string,
category: {
id: string
name: string,
}
}
I want to have column that bind to productCategory.name. However that field is nullable. When productCategory is null/undefined, kendo will throw error. How can i tell kendo that if field is undefined, just show empty string?
EDIT
Below is my sample data
[{
"id":1,
"name":"Spaghetti",
"category":{
"id":"1",
"name":"Food"
}},
{
"id":2,
"name":"Coca-cola",
"category":null
}}]
Below is my kendo datasource
var kendoDataSource = new kendo.data.DataSource({
schema: {
data: "data",
total: "total",
model: {
id: "id",
fields: {
id: { type: "string" },
name: { type: "string" },
"category.name": { type: "string" }
}
}
}
});
Data above will throw "undefined" error, because second product does not have category.
Try using empty object instead of null
created a fiddle,check this:
http://jsfiddle.net/Sowjanya51/h930jcru/
Just provide a default value in your model like this:
var kendoDataSource = new kendo.data.DataSource({
schema: {
data: "data",
total: "total",
model: {
id: "id",
fields: {
id: { type: "string" },
name: { type: "string" },
"category.name": { type: "string" },
category: { defaultValue: {
id: "",
name: "",
}
}
}
}
}
});
This will initialize productCategory if it is null or undefined.

Resources