I'm working in a backend with NodeJS and Mysql, everything is good but recently I've faced a small details where I'm stuck since added a SUBQUERY.
This is the Mysql Query:
var GetHistoryPayments = function(code){
var query = "SELECT DISTINCT students.student_code, " +
"acc.id, " +
"acc.StudentCode, " +
"acc.DocumentDate1, " +
"acc.DocEntry, " +
"acc.DocumentNumber1, " +
"acc.DocTotal1, " +
"acc.GrosProfit, " +
"acc.SumApplied, " +
"acc.DocumentDate2, " +
"acc.DocumentNumber2, " +
"acc.DiffDocTotalPaidToDate as total_pay, " +
"acc.LicTradNum, " +
"acc.created_at, " +
"acc.updated_at, " +
"(SELECT COUNT(*) FROM sap_accounting_state aa WHERE aa.DocumentNumber1 = acc.DocumentNumber1 and aa.tipo like 'Nota%' and aa.SumApplied > 0 ) as credit_notes " +
"FROM sap_accounting_state_students students INNER JOIN sap_accounting_state acc ON students.student_code = acc.StudentCode " +
"WHERE acc.DiffDocTotalPaidToDate = 0 " +
"and acc.Orden = 1 " +
"and acc.DocumentDate1 > '2018-06-01' " +
"and acc.StudentCode = '" + code + "' " +
"GROUP BY acc.DocumentNumber1 " +
"ORDER BY acc.DocumentDate1 desc";
return query;
}
The Object array returned is ok, but the SUBQUERY Object is really weird, it returns with a empty name ('': { credit_notes: 0 }). I suppose the SUBQUERY creates a new object with a known name. ¿How could access a '' json element?, how could put a name SUBQuery like: 'sub': { credit_notes: 0 }?.
Thanks.
[ RowDataPacket {
students: { student_code: '18018' },
acc:
{ id: 3836,
StudentCode: '18018',
DocumentDate1: 2019-01-01T05:00:00.000Z,
DocEntry: 74998,
DocumentNumber1: 10042438,
DocTotal1: 1839017,
GrosProfit: 1839017,
SumApplied: 0,
DocumentDate2: null,
DocumentNumber2: 0,
total_pay: 0,
LicTradNum: '79593354',
created_at: 2019-01-18T19:48:23.000Z,
updated_at: 2019-01-18T19:48:23.000Z },
'': { credit_notes: 0 } },
RowDataPacket {
students: { student_code: '18018' },
acc:
{ id: 3842,
StudentCode: '18018',
DocumentDate1: 2018-12-06T05:00:00.000Z,
DocEntry: 72048,
DocumentNumber1: 10039576,
DocTotal1: 346500,
GrosProfit: 346500,
SumApplied: 0,
DocumentDate2: null,
DocumentNumber2: 0,
total_pay: 0,
LicTradNum: '79593354',
created_at: 2019-01-18T19:48:23.000Z,
updated_at: 2019-01-18T19:48:23.000Z },
'': { credit_notes: 1 } } ... ]
Just take brackets as property accessor.
var item = { '': 'foo' };
console.log(item['']);
Related
I have an exercise where from an object constructor, I have created several objects, all with an ID property.
The first part of the exercise consist in pairing each object, compare their markAv properties and print the one that had it bigger.
[ a vs b => b wins]
They suggested to do so by using the ID property but I didn't know how to do it that way... so I tried a workaround, as you will see in the code below.
However, the second part of the exercise wants me to do the same but, this time, creating the pairs randomly. Here I have tried to use the ID property by generating a random number that matches the ID but I don´t know how to structure the code for it to work.
The output for the second part should be the same as above, with the only difference that the pairing is now randomly generated.
I have added a partial solution for the second part, partial because from time to time it throws an error that I can´t identify. However, I think I'm getting close to get my desired output.
I would really appreciate if anyone could give me a hint for me to crack the code below and to get it working because I really want to understand how to do this.
class Avenger {
constructor(name, classRoom, city, job, studies, markAv, id) {
this.name = name;
this.classRoom = classRoom;
this.city = city;
this.job = job;
this.studies = studies;
this.markAv = markAv;
this.id = id;
}
heroList() {
return this.name + " " + this.classRoom + " " + this.city + " " + this.job + " " + this.studies + " " + this.markAv + " " + this.id
}
}
const tonyStark = new Avenger("Tony Stark", "XI", "NYC", "Ingeneer", "MIT", 10, 1)
const hulk = new Avenger("Hulk", "X", "Toledo", "Destroyer", "Scientific", 7, 2)
const daredevil = new Avenger("Daredevil", "IX", "NYC", "Lawyer", "Fighter", 2, 3)
const magneto = new Avenger("Magneto", "XXI", "SBD", "Unemployed", "Driver", 5, 4)
const unknown = new Avenger("Unknown", "L", "CDY", "President", "Clerck", 17, 5)
const xavi = new Avenger("Xavi", "XX", "BCN", "Analist", "Calle", 7, 6)
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
function getPairs(array) {
function getPairs(array) {
for (let i = 0; i < array.length; i += 2) {
if (array[i].markAv < array[i + 1].markAv) {
console.log(array[i].name + " vs " + array[i + 1].name + " " + array[i + 1].name + " Wins")
} else if (array[i].markAv > array[i + 1].markAv) {
console.log(array[i].name + " vs " + array[i + 1].name + " " + array[i].name + " Wins")
}
}
}
getPairs(heroes)
///
function randomAv(array) {
let result = []
let hero1 = heroes[Math.floor(Math.random() * 6) + 1]
for(let i = 0; i<array.length; i++){
if (array[i].markAv <= hero1.markAv && array[i].id != hero1.id) {
result.push(console.log(array[i].name + " vs " + hero1.name + " " + array[i].name + " Wins"))
} else if(array[i].markAv >= hero1.markAv && array[i].id != hero1.id) {
result.push(console.log(array[i].name + " vs " + hero1.name + " " + hero1.name + " Wins"))
}
}
console.log(result)
}
First shuffle the array:
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
let heroes_shuffle = heroes.sort((a, b) => 0.5 - Math.random())
Then do as normal
getPairs(heroes_shuffle )
All Possible Combination :
function allPairs(heroes) {
while (heroes) {
[hero, ...heroes] = heroes
for (enemy of heroes) {
if (hero.markAv === enemy.markAv)
console.log(hero.name + " vs " + enemy.name + ": draw")
else if (hero.markAv < enemy.markAv)
console.log(hero.name + " vs " + enemy.name + ": " + enemy.name + " Wins")
else
console.log(hero.name + " vs " + enemy.name + ": " + hero.name + " Wins")
}
}
}
You can take the function from here https://stackoverflow.com/a/7228322/1117736
And do something like this:
class Avenger {
constructor(name, classRoom, city, job, studies, markAv, id) {
this.name = name;
this.classRoom = classRoom;
this.city = city;
this.job = job;
this.studies = studies;
this.markAv = markAv;
this.id = id;
}
heroList() {
return this.name + " " + this.classRoom + " " + this.city + " " + this.job + " " + this.studies + " " + this.markAv + " " + this.id
}
}
const tonyStark = new Avenger("Tony Stark", "XI", "NYC", "Ingeneer", "MIT", 10, 1)
const hulk = new Avenger("Hulk", "X", "Toledo", "Destroyer", "Scientific", 7, 2)
const daredevil = new Avenger("Daredevil", "IX", "NYC", "Lawyer", "Fighter", 2, 3)
const magneto = new Avenger("Magneto", "XXI", "SBD", "Unemployed", "Driver", 5, 4)
const unknown = new Avenger("Unknown", "L", "CDY", "President", "Clerck", 17, 5)
const xavi = new Avenger("Xavi", "XX", "BCN", "Analist", "Calle", 7, 6)
let heroes = [daredevil, hulk, tonyStark, magneto, unknown, xavi]
function randomIntFromInterval(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min)
}
let hero1 = heroes[randomIntFromInterval(1, 6)]
let hero2 = heroes[randomIntFromInterval(1, 6)]
if (hero1.markAv < hero2.markAv) {
console.log(hero1.name + " vs " + hero2.name + " " + hero1.name + " Wins")
} else if(hero1.markAv > hero2.markAv) {
console.log(hero1.name + " vs " + hero2.name + " " + hero2.name + " Wins")
}
I need an autocomplete text box for my search and I will use jQuery UI for this. I'm using an ASP.NET Core API to get search result in json format. My search result should be grouping with bootstrap collapse panel and group members showing in a table. Every group has different fields and then has different tables. What is the best solution for this case? Thanks.
$('#SearchTextBox').autocomplete({
source: 'api/user/search/'
});
My answer may be super late. But i hope this would help some one else. Basically i created this in mvc-5. You should modify it according to your needs.
$("#txtsearchpatient").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("SearchPatient")',
dataType: "json",
data: { search: $("#txtsearchpatient").val() },
success: function (data) {
if (data.length > 0) {
response($.map(data, function (item) {
return {
id: item.Id,
value: item.Name
};
}));
}
else {
$("#emptysearchdiv").hide();
var result = [
{
id:0,
label: 'No matches found',
value: ""
}
];
response(result);
}
},
error: function (xhr, status, error) {
}
});
},
autoFocus: true,
select: function (event, ui) {
$(this).val(ui.item.value);
var value = ui.item.value;
var id = ui.item.id;
},
search: function (e, u) {
$(this).addClass('loader');
},
response: function (e, u) {
$(this).removeClass('loader');
}
});
public JsonResult SearchPatient(string search)
{
Regex RE_Numbers = new Regex(#"^\d+$");
if(RE_Numbers.IsMatch(search) == true)
{
var sdsds = db.Patient.Where(x =>
x.PhoneNumber.Contains(search)).Select(x => new {
Id = x.Id,
Name = "Name: " + x.Name + " | " + "EmailId: " + x.EmailId + " | " +
"Phone: " + x.PhoneNumber + " | " + "Age: " + x.Age
}).ToList();
return Json(sdsds, JsonRequestBehavior.AllowGet);
}
else if(search.Contains("#") == true || search.Contains(".com") == true)
{
var sdsds = db.Patient.Where(x => x.EmailId.Contains(search)).Select(x =>
new {
Id = x.Id,
Name = "Name: " + x.Name + " | " + "EmailId: " + x.EmailId + " | " +
"Phone: " + x.PhoneNumber + " | " + "Age: " + x.Age
}).ToList();
return Json(sdsds, JsonRequestBehavior.AllowGet);
}
else
{
var sdsds = db.Patient.Where(x => x.Name.Contains(search)).Select(x =>
new {
Id = x.Id,
Name = "Name: " + x.Name + " | " + "EmailId: " + x.EmailId + " | " +
"Phone: " + x.PhoneNumber + " | " + "Age: " + x.Age
}).ToList();
return Json(sdsds, JsonRequestBehavior.AllowGet);
}
}
is there a standard established way to do the following:
curl -i "http://api.waqi.info/feed/shanghai/?token=demo"
returns
{
status: "ok",
data: {
aqi: 70,
time: {
s: "2016-12-11 12:00:00"
},
city: {
name: "Shanghai",
url: "http://aqicn.org/city/shanghai/",
geo: [
"31.2047372",
"121.4489017"
]
},
iaqi: {
pm25: "..."
}
}
}
i want to make a simple page that calls the API and formats the result. but i want to do it in the browser so that i can host a serverless webpage.
Ive look at Angular and react but it seems an awful lot of setup and baggage to do something simple like this.
i could write the jscript and html from scratch but also feels like there should be some libraries to support this.
You can write an ajax call to get the data like this:
fetch('http://api.waqi.info/feed/shanghai/?token=demo')
.then(function(response) {
return response.json();
})
.then(function(jsonData) {
console.log(jsonData); //the data you want to get
});
More information here
If you want to use some library, you can try superagent
I have used jQuery plugin and used $.ajax() method: See here.
Later, I split all data using keys as shown below;
$.ajax({
url: 'http://api.waqi.info/feed/shanghai/?token=demo',
success: function(ajax) {
console.log(ajax);
let data = ajax.data; // Object
let api = data.api; // Int
let attributions = data.attributions; // Array [3]
let cityCoords = data.city.geo; // Array [2]
let cityName = data.city.name; // String
let cityUrl = data.city.url; // String
let dominentpol = data.dominentpol; // String
let iaqi = data.iaqi; // Object Keys = [co, d, h, no2, o3, p ,pm10, pm25, so2, t, w, wd]
let idx = data.idx; // Int
let time = data.time; // Object Keys = [s, tz, v]
let status = ajax.status;
console.log("Data Object: "
+ data +
"\nAPI Version: "
+ api +
"\nAttributions #1 Name: "
+ attributions[0].name +
"\nAttributions #1 Url: "
+ attributions[0].url +
"\nAttributions #2 Name: "
+ attributions[1].name +
"\nAttributions #2 Url: "
+ attributions[1].url +
"\nAttributions #3 Name: "
+ attributions[2].name +
"\nAttributions #3 Url: "
+ attributions[2].url +
"\nCity Longitude: "
+ cityCoords[0] +
"\nCity Latitude: "
+ cityCoords[1] +
"\nCity Name: "
+ cityName +
"\nCity Url: "
+ cityUrl +
"\dDominentpol: "
+ dominentpol +
"\nIaqi Key [co]: "
+ iaqi.co +
"\nIaqi Key [d]: "
+ iaqi.d +
"\nIaqi Key [h]: "
+ iaqi.h +
"\nIaqi Key [no2]: "
+ iaqi.no2 +
"\nIaqi Key [o3]: "
+ iaqi.o3 +
"\nIaqi Key [p]: "
+ iaqi.p +
"\nIaqi Key [pm10]: "
+ iaqi.pm10 +
"\nIaqi Key [pm25]: "
+ iaqi.pm25 +
"\nIaqi Key [so2]: "
+ iaqi.so2 +
"\nIaqi Key [t]: "
+ iaqi.t +
"\nIaqi Key [w]: "
+ iaqi.w +
"\nIaqi Key [wd]: "
+ iaqi.wd +
"\nIdx: "
+ idx +
"\nTime Key = [s]: "
+ time.s +
"\nTime Key = [tz]:"
+ time.tz +
"\nTime Key = [v]:"
+ time.v +
"\nStatus: "
+ status);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am creating an object from a json file events.json using lodash map and uniqby.
Very rarely I get an event that has a country other than "United Kingdom". I don't need them in the results, how would I go about 'not mapping' the events that are not in the "United Kingdom". Thanks
var _ = require('lodash');
var data = require('./events.json')
var newEventList = _.uniqBy(data.events,'id').map(events => ({
id: events.id ,
name: events.name ,
venue: events.venue.name ,
address: events.place.location.street + " " + events.place.location.city + " " + events.place.location.zip + " " + events.place.location.country
}));
I have looked at _.filter but am not sure of where to use it within the map function.
You can use filter before or after map. But before map it will be more useful.
var newEventList = _.uniqBy(data.events,'id').filter(event => event.place.location.country === 'United Kingdom').map(event => ({
id: event.id ,
name: event.name ,
venue: event.venue.name ,
address: event.place.location.street + " " + event.place.location.city + " " + event.place.location.zip + " " + event.place.location.country
}));
But the question is why you need uniq by id? Usually id is a property that should be uniq
What I have,
var oldUsers = [{
"SID": "S-12",
"Username": "bring.on",
"firstname": "bring",
"lastname": "on",
"email": "emasdklhsjas#gmnailasd.com"
// and so on... 10 more properties
}, {
"SID": "S-13",
"Username": "bring.on1",
"firstname": "bring",
"lastname": "on1",
"email": "sdf#gmnailasd.com"
// and so on... 10 more properties
},
// n numbers of more users...];
What I want,
var newUsers = [{ FullName : "bring on - emasdklhsjas#gmnailasd.com",
value : S-12
},
{ FullName : "bring on1 - sdf#gmnailasd.com",
value : S-13
}, // more users with same properties as abvove
];
What I tried but failed,
var newUsers = $.each(oldUser, function () {
return u = {
value : this.SID,
FullName : this.firstname + " " + this.lastname + " - " + this.email,
};
});
It needs to work on IE-8+ not sure what I am doing wrong really.
All I want is to reduce properties of object in array and get a new object.
Array.prototype.map() can be used to create new array using Plain old Vanilla JavaScript.
The map() method creates a new array with the results of calling a provided function on every element in this array
var newUsers = oldUser.map(function(obj){
return {
value : obj.SID,
FullName : obj.firstname + " " + obj.lastname + " - " + obj.email,
}
});
Note: It will work with IE9+
Using jQuery.map()
var newUsers = jQuery.map(oldUser, function(obj){
return {
value : obj.SID,
FullName : obj.firstname + " " + obj.lastname + " - " + obj.email,
}
});
Your problem is that the .each function doesn't return anything.
http://api.jquery.com/jquery.each/. It iterates over the collection of objects and performs and action on each one. This is different than the functional concept of the higher order function map, which is used to translate one collection into another. (JQuery has a map function too.)
To fix your problem you either need to do:
var newArray = []
var newUsers = $.each(oldUser, function () {
newArray.push ({
value : this.SID,
FullName : this.firstname + " " + this.lastname + " - " + this.email,
});
});
or
var newArray = $.map(oldUsers, function (u,i) {
return {
value : this.SID,
FullName : u.firstname + " " + u.lastname + " - " + u.email,
};
});
Personally, I would go with the second one, as it reduces the number of side effects in your code.
Edit: Apparently, map does not work in IE 8, so the top one is the more correct approach.
Try the following:
var newUsers = [];
$.each(oldUser, function () {
newUsers.push({
value : this.SID,
FullName : this.firstname + " " + this.lastname + " - " + this.email,
});
});
Here is a fiddle for it. Check your console log for the outcome when you run the fiddle.
try this!
var newArr= [];
$.each(users, function (index , user) {
newArr.push({
value : user.SID,
FullName : user.firstname + " " + user.lastname + " - " + user.email,
});
});
Your object is an array of objects, so make use of Array map method:var result = oldUsers.map(function(e){
return { Fullname : e.firstname + e.lastname, value : e['SID']};
});