Display only certain keys in json response - json

I'm building a simple API with express and sqlite. I want my GET request to only display certain keys in each JSON object that is displayed in response.
Below is my current code:
router.get('/cars', (req, res) => {
// TODO GET all cars
try {
let sql = 'SELECT * FROM cars'
let params = []
db.all(sql, params, (err, rows) => {
if (err) {
res.status(400).json({"error":err.message});
return;
}
else {
res.status(200).json({
message: 'success',
data: rows
})
}
});
} catch(error) {
console.log(error.message.red)
res.status(500).json({
message: 'Not found.'
})
}
})
Right now, the response will display entries from the database with all keys and their values. It looks like this:
{
"message": "success",
"data": [
[
{
"car_id": 48,
"email": "honoland13#japanpost.jp",
"name": "Hernando",
"year": 2015,
"make": "Acura",
"model": "TLX",
"racer_turbo": 0,
"racer_supercharged": 0,
"racer_performance": 2,
"racer_horsepower": 2,
"car_overall": 4,
"engine_modifications": 4,
"engine_performance": 0,
"engine_chrome": 2,
"engine_detailing": 4,
"engine_cleanliness": 4,
"body_frame_undercarriage": 2,
"body_frame_suspension": 4,
"body_frame_chrome": 2,
"body_frame_detailing": 2,
"body_frame_cleanliness": 2,
"mods_paint": 2,
"mods_body": 2,
"mods_wrap": 0,
"mods_rims": 4,
"mods_interior": 4,
"mods_other": 4,
"mods_ice": 6,
"mods_aftermarket": 2,
"mods_wip": 0,
"mods_overall": "4",
"score": 62
},
...
I just want to display the car_id, email, name, year, make, model, and score keys and their values and omit the rest of the keys.
I've tried using a forEach loop like so
if(err) {
res.status(400).json({'error':err.message});
return;
} else {
res.json({
message:'success',
data: rows.forEach((row) => {
row.car_id,
row.email,
row.name,
row.year,
row.make,
row.model,
row.score
}
})
}
But it doesn't show the data, but I'm not getting any errors in my console either.
Expected output is this:
"message": "success",
"data": [
[
{
"car_id": 48,
"email": "honoland13#japanpost.jp",
"name": "Hernando",
"year": 2015,
"make": "Acura",
"model": "TLX",
"score": 62
},
...
Any help is really appreciated.

try this
let sql = 'SELECT car_id,email,name,year,make,model,score FROM cars'

Related

Filter to retrieve specific value in nested object using Vue

I have a nested json object:
{
"51": {
"wheels": 10,
"id": 1,
"name": "truck"
},
"55": {
"wheels": 4,
"id": 33,
"name": "Car"
},
"88": {
"wheels": 2,
"id": 90,
"name": "Bike"
}
}
I would like to filter by ID but only return the wheels so ie.
Filter ID = 33 which would return 4.
I have tried using the .filter function but I get an error: filter is not a function which I assume is because this is not an array. I have tried to replicate using answer here:
How to filter deeply nested json by multiple attributes with vue/javascript
Without success because the json has a key (51, 55, 88) so I am stumped.
Thanks for the help in advance.
You can use Object.values to convert the object into an array and then use find method on it to retrieve the specific object. Something like:
Object.values(obj).find(val => val.id === 33)?.wheels
let obj = {
"51": {
"wheels": 10,
"id": 1,
"name": "truck"
},
"55": {
"wheels": 4,
"id": 33,
"name": "Car"
},
"88": {
"wheels": 2,
"id": 90,
"name": "Bike"
}
}
console.log(Object.values(obj).find(val => val.id === 33)?.wheels)

ERROR Error: "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."

I have following problem: I try to get the values of "place" with ngfor.
Following i use:
.html
<ng-container *ngFor="let se of List"
Following Json:
.json
"place": [
{
"id": 1,
"name": "Ort",
"number": "Nummer",
"type": "Art",
"height": 20,
"width": 42,
"lagerin": [
{
"id": 1,
"secnname": "Regal ",
"secnnumber": "R1",
"sectype": {
"sectypename": "Big ",
"ro": 5,
"co": 2,
"secheight": 20,
"secwidth": 6,
"secdepth": 1,
"sectco": 1
}
},
{
"id": 2,
"secnname": "Reg 2 ",
"secnnumber": "R2",
"sectype": {
"sectypename": "Small",
"ro": 3,
"co": 3,
"secheight": 25,
"secwidth": 4,
"secdepth": 2,
"sectco": 2
}
}
]
}
]
I get the error above. So my idea is to get the attributes in "place" to use them in my code.
It was working fine, before i add "lagerin". But i need this one in "place".
.ts
ngOnInit() {
this.route.queryParams
.subscribe(params => {
this.id = params.id;
});
if (this.id) {
this.service.gelager(this.id).subscribe(data => {
if (data) {
this.List= data;
} else {
console.log('No lager available');
}
});
}
}
If your getLager method returns the Json you showed us then you should have
this.list = data.place
And your local variables should not start with a capital letter, it is just a convention

How to retrive data from multiple tables. Using node js and mysql?

I have two tables which are give in at this fiddle.
http://sqlfiddle.com/#!9/d37102
I want to retrieve data from the table currently I am doing this way
mysqlConnection.query("SELECT* FROM wallet WHERE user_id = ? ORDER by date",authData.id,(err,rows,fields)=>{
if(!err){
res.json({
message :"Statement",
rechargeDetails : rows,
transactionDetail://// TODO: Transaction details
});
}
else console.log(err);
});
That is correctly retrieving the JSON data in at this format over here
{
"message": "Statement",
"rechargeDetails": [
{
"id": 17,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
},
{
"id": 18,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
}
]
}
I want to get transaction table data also like this
{
"message": "Statement",
"rechargeDetails": [
{
"id": 17,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
},
{
"id": 18,
"amount": 50,
"type": "CREDIT",
"pg_id": "xxxxq123",
"comments": null,
"intrument_type": "REFUND",
"user_id": 1,
"date": "2020-04-17T18:30:00.000Z"
}
"transactionDetails": [
{
"id": 17,
"amount": 50,
"tax": "CREDIT",
"discount": "xxxxq123",
"adjustment": null,
"refrence_id": "REFUND",
"payment_ref_id": 1,
xxxxxx
xxxxxxxxxx
}
],
}
How could i do that? Is there a way to do this?
mysqlConnection.query("SELECT * FROM wallet WHERE user_id = ? ORDER by date",authData.id,(err,rows,fields)=>{
if(!err){
mysqlConnection.query("SELECT * FROM transaction WHERE user_id = ? ORDER by date",authData.id,(errTarn,rowsTarn,fieldsTarn)=>{
if(!errTarn){
res.json({
message :"Statement",
rechargeDetails : rows,
transactionDetail: rowsTarn
});
}
});
}
else console.log(err);
});
OR YOU CAN USE MULTIPLE QUERY
enable it for your connection
var connection = mysql.createConnection({multipleStatements: true});
Now the code will be
connection.query('SELECT * FROM wallet WHERE user_id = ? ORDER by date; SELECT * FROM transaction WHERE user_id = ? ORDER by date', [authData.id, authData.id], function(err, results) {
if (err) throw err;
if(!err){
res.json({
message :"Statement",
rechargeDetails : results[0],
transactionDetail: results[1]
});
}
});
I have zero knowledge with NODE but I think something like this should work properly
mysqlConnection.query("SELECT* FROM wallet WHERE user_id = ? ORDER by date",authData.id,(err,rows,fields)=>{
if(!err){
res.json({
message :"Statement",
rechargeDetails : rows,
transactionDetail: mysqlConnection.query("__SELECT_TRANSACTIONS_QUERY__",authData.PARAMETER_NEEDED,(err,rows,fields)=>{
if(!err){
// return your rows
}
});
});
} else {
console.log(err);
}
});

Unable to get the length of JSON object

I am getting 'TypeError: Cannot convert undefined or null to object' while trying to access the length of json object in nodejs.
Following is how my data looks like:
{
"college": [
{
"colleges": [],
"department": [
1,
2,
3
],
"general_course": [],
"id": 1,
"name": "College of the Arts",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1919"
},
{
"colleges": [],
"department": [
4,
5,
6
],
"general_course": [],
"id": 2,
"name": "College of Communications",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1920"
},
{
"colleges": [],
"department": [
7,
12
],
"general_course": [],
"id": 3,
"name": "College of Education",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1921"
},
{
"colleges": [],
"department": [
13,
17,
19
],
"general_course": [],
"id": 4,
"name": "College of Engineering and Computer Science",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1922"
},
{
"colleges": [],
"department": [
20,
26,
27
],
"general_course": [],
"id": 5,
"name": "College of Health and Human Development",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1923"
},
{
"colleges": [],
"department": [
28,
29,
32,
48
],
"general_course": [],
"id": 6,
"name": "College of Humanities and Social Sciences",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1924"
},
{
"colleges": [],
"department": [
52,
57
],
"general_course": [],
"id": 7,
"name": "College of Natural Sciences and Mathematics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1925"
},
{
"colleges": [],
"department": [
58,
59,
63
],
"general_course": [],
"id": 8,
"name": "Mihaylo College of Business and Economics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1926"
}
]
}
Step 1 - Parsing it into nodejs:
let colleges = JSON.parse(data)
Step 2 - Saving it into the dialogflow app data:
app.data.collegeData = data;
Step 3 - Accessing the length:
let collegeLength = Object.keys(app.data.collegeData.college).length;
Getting following error in firebase console:
TypeError: Cannot convert undefined or null to object
Update:
Here is the code:
if ( app.data.collegeData === undefined ){
app.data.collegeData = [];
}
**Step 1 =>**
showColleges(college);
**Step 2 =>**
function showColleges(collegeName){
if (app.data.collegeData.length === 0){
getCollegeData().then(buildSingleCollegeResponse(collegeName))
.catch(function (err){
console.log('No college data')
console.log(err)
});
}
else{
buildSingleCollegeResponse(collegeName);
}
}
**Step 3 =>**
function getCollegeData(){
console.log('Inside get College Data')
return requestAPI(URL)
.then(function (data) {
let colleges = JSON.parse(data)
if (colleges.hasOwnProperty('college')){
saveData(colleges)
}
return null;
})
.catch(function (err) {
console.log('No college data')
console.log(err)
});
}
**Step 4 =>**
function saveData(data){
app.data.collegeData = data;
console.log(app.data.collegeData)
}
**Step 5 =>**
function buildSingleCollegeResponse(collegeName){
let responseToUser, text;
//console.log('Data is -> '+ Object.keys(app.data.collegeData.college).length);
//console.log('Length is -> '+ app.data.collegeData.college.length);
console.log('Count is -> '+app.data.collegeCount);
let collegeLength = Object.keys(app.data.collegeData.college).length;
if ( collegeLength === 0){
responseToUser = 'No colleges available at this time';
text = 'No colleges available at this time';
}
else if ( app.data.collegeCount < collegeLength ){
for ( var i = 1; i <= collegeLength; i++)
{
console.log('All Colleges:: '+app.data.collegeData.college[i])
let coll = app.data.collegeData.college[i]
let name = coll.name
console.log('checkCollegeExist => College Name:: '+ name)
console.log('checkCollegeExist => Parameter => College Name:: '+collegeName)
if(String(name).valueOf() === String(collegeName).valueOf()){
responseToUser = 'Yes! CSUF has '+collegeName;
text = 'Yes! CSUF has '+collegeName;
}else{
responseToUser = 'CSUF does not teach ' +collegeName+' currently';
text = 'CSUF does not teach ' +collegeName+' currently';
}
}
}
else{
responseToUser = 'No more colleges';
}
if (requestSource === googleAssistantRequest) {
sendGoogleResponse(responseToUser);
} else {
sendResponse(text);
}
}
This is the culprit:
getCollegeData().then(buildSingleCollegeResponse(collegeName))
That calls buildSingleCollegeResponse(collegeName) and then passes its return value into then, just like foo(bar()) calls bar and passes its return value into foo.
You wanted to pass a functon to then:
getCollegeData().then(() => buildSingleCollegeResponse(collegeName))
// An arrow function ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note that now that it's clear from the updated question that app.data.collegeData.college is an array, there's no need for Object.keys. Change:
let collegeLength = Object.keys(app.data.collegeData.college).length;
to simply
let collegeLength = app.data.collegeData.college.length;
Arrays have a length property (whereas non-array objects don't, by default).
You haven't mentioned what value app.data holds before issuing app.data.collegeData = data;
If app.data is undefined you should try app.data = {collegeData: data}
Or else negating what app stores. Following works
app = {};
app.data = {};
app.data.collegeData = data;
app.data.collegeData.college.length
You don't need to do the following
let collegeLength = Object.keys(app.data.collegeData.college).length;
Update: Refer to https://jsfiddle.net/dmxuum79/3/

How to chain sql queries which are dependent on each other in node

I am looking to fetch data from on query and then run a array loop over a item stored in result. then Fetch data from another query using keys from the array fetched from first query.
What ever I have tried is not giving me the desired result as array loops runs out before the sql queried finishes and produce the desired result.
I have tried solution with async.series function and async.map function but result is not coming in the desired sequence.
This is the output From first query.
My objective is to add array of option details in place option id which is returned from first query.
[
{
"id": 318,
"name": "Sandwich Dosa",
"price": 140,
"option": ''
},
{
"id": 319,
"name": "Spi. Prem Uttappa",
"price": 131,
"option": '1,2'
},
{
"id": 320,
"name": "Paneer Spl. Prem Uttappa",
"price": 140,
"option": ''
},
{
"id": 321,
"name": "Spl. Spicy Uttappa",
"price": 131,
"option": ''
}
]
Looking to build as
[
{
"id": 318,
"name": "Sandwich Dosa",
"price": 140,
"option": ''
},
{
"id": 319,
"name": "Spi. Prem Uttappa",
"price": 131,
"option": [{
id:'1',
name:'Regular',
price:'89',
},
{
id:'2',
name:'Spicy',
price:'119',
}]
},
{
"id": 320,
"name": "Paneer Spl. Prem Uttappa",
"price": 140,
"option": ''
},
{
"id": 321,
"name": "Spl. Spicy Uttappa",
"price": 131,
"option": ''
}
]
This is my current code through which I am trying to achive
var data = {
"error": 1,
"items": ""
};
connection.query("SELECT * FROM items WHERE status=1 AND menu_grp_id=" + req.params.sid, function(err, rows, fields) {
var items = []; // temporary holder for items
if(err) { throw err } else {
if(rows.length != 0) {
for (var key in rows) {
// Holding Item properties
var item = {
id: '',
name: '',
price: '',
option: ''
};
item.id = rows[key].id;
item.name = rows[key].item_name;
item.price = rows[key].price;
item.option = rows[key].option;
items.push(item); // pushing item object into items array
}
data["error"] = 0;
data['items'] = items;
if((data['items'].length > 0)) {
for(i = 0; i < data['items'].length; i++) {
if(data['items'][i].option == "") {
data['items'][i].option = [];
} else {
var array = data['items'][i].option.split(",")
data['items'][i].option = array;
}
}
}
res.json(data); // sending JSON Data
} else {
data["error"] = 0;
data["items"] = 'No item Found..';
res.json(data); // sending JSON Data
}}
});
Probably I'm a bit late here, but I think that async.waterfall is what you need.
async.waterfall([
function(cb){
connection.query("SELECT * FROM items WHERE status=1 AND menu_grp_id=" + req.params.sid, function(err, rows, fields) {
//manipulate your data as you wish
data = synchronousManipolutionOfYourData();
cb(null, data);
});
},
function(data, cb){
//data here stores the data you passed as a second parameter in the preciding callback
//execute your second query with the data you got from the first query.
cb(null, dataManipulatedAfterSecondQuery)//and so on
},
//other functions if you need other queries
], function(){
done;
});