I need to fetch that 2nd query "Total Job" column with the first query as per the account_id is the primary key. How can I combine this two queries?
This is my Typescript NodeJS and mysql Rest API. How can I get this result?
const getPremiumJob = async (req: Request) => {
const connection = await createConnection()
try {
console.log(1)
const [premiumJob]: any = await connection.query(`SELECT rafp.account_id,rafp.foa_property_id,fpl.name,
rafp.text_value,rafp.int_value,rafp.float_value, fp.datatype FROM
rel_account_foa_property rafp join foa_property_localization fpl on rafp.foa_property_id=fpl.foa_property_id join
account on account.account_id=rafp.account_id inner join foa_property fp on fp.foa_property_id=rafp.foa_property_id where
fpl.name IN ('job title','enterprise','job description','job description','adress','image','job type','company_youtube','cover image') order by rafp.account_id ;`)
// const [premiumJob]: any = await connection.query(`SELECT t.tender_id,fpl.foa_property_id,fpl.name,rtfp.text_value,rtfp.int_value,rtfp.float_value, fp.datatype FROM tender t
// inner join rel_tender_foa_property rtfp on t.tender_id= rtfp.tender_id inner join foa_property_localization fpl on fpl.foa_property_id=rtfp.foa_property_id
// inner join foa_property fp on fp.foa_property_id=rtfp.foa_property_id `)
const [premiumJobCount]: any = await connection.query(` SELECT rel_account_foa_property.account_id,rel_account_foa_property.foa_property_id,rel_account_foa_property.text_value as "company name",COUNT(text_value) as "Total Job" FROM rel_account_foa_property join foa_property_localization on rel_account_foa_property.foa_property_id=foa_property_localization.foa_property_id join account on account.account_id=rel_account_foa_property.account_id where
foa_property_localization.name="enterprise" group by rel_account_foa_property.account_id,rel_account_foa_property.foa_property_id;`)
console.log(premiumJob)
const values = premiumJob.reduce((prev: any, curr: any) => ({
...prev,
[curr.account_id]: {
account_id: curr.account_id,
...prev[curr.account_id],
[(curr.name).replaceAll(' ', "_")]: curr[`${curr.datatype}_value`],
}
}), {}
as Record < string, any > )
return Object.values(values)
} catch (error) {
await connection.end()
throw error
}
}
I am getting below this result when I excecated first query
{
"account_id": 2641,
"job_title": "test1",
"enterprise": "hh",
"job_description": "test1",
"adress": "bangalore",
"image": "http://localhost:3005/public/uploads/company-logos/undefined",
"job_type": "top",
"company_youtube": "test2",
"cover_image": "http://localhost:3005/public/uploads/company-logos/undefined"
}
I Need also Total Job from the second query add with this above query account_ID
I expected output is given below
{
"account_id": 2639,
"job_title": "test1",
"enterprise": "hh",
"job_description": "test1",
"adress": "bangalore",
"image": "http://localhost:3003/public/uploads/company-logos/undefined",
"job_type": "top",
"company_youtube": "test2",
"cover_image": "http://localhost:3003/public/uploads/company-logos/undefined",
"Total Job": 1
}, {
"account_id": 2641,
"job_title": "test1",
"enterprise": "hh",
"job_description": "test1",
"adress": "bangalore",
"image": "http://localhost:3005/public/uploads/company-logos/undefined",
"job_type": "top",
"company_youtube": "test2",
"cover_image": "http://localhost:3005/public/uploads/company-logos/undefined",
"Total Job": 1
}
I have an object result which has a property records which is an array of objects with a single sample below:
const result = {
records: [
{
keys: ["names", "value", "country", "questions"],
length: 4,
_fields: [
"123ilSE",
[
"Longitude:5.1193",
"Latitude:52.3246",
"Agreeableness:0.147083333333333",
"Openness:0.211041666666667",
"Neuroticism:0.168833333333333",
"Extraversion:0.150291666666666",
"Conscientiousness:0.187041666666666",
"Angry:0.0441711768507957",
"Fear:0.020498564466834",
"Joy:0.875858068466186",
"Sadness:0.0477884039282798",
"Love:0.00839435961097478",
],
["Netherlands", "Netherlands"],
[
["Right"],
["Student Loan", "None"],
["Not at all, i’d rather rent all assets."],
["Another benefit"],
["Every two weeks", "Yearly a few times"],
[
"None",
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
["Two to Three Times a Week"],
[
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
[
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
[
"None",
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
["Every two weeks", "Yearly a few times"],
["Two to Three Times a Week"],
["Every Year"],
["Banking & Financial Services", "Unemployed"],
["I don't have a car"],
["Netherlands", "Netherlands"],
["3 - 4 persons"],
["Maybe, it depends if nothing betters comes up"],
["Desktop"],
[],
["I don't drive or have a car"],
[
"E, I can be found on social media platforms and maintain my profile but do little else.",
],
["None", "Healthcare Insurance"],
["None", "Hockey", "Hiking"],
["Hiking"],
["Unemployed"],
["1999-09-20 00:00:00"],
["Female"],
["Bachelor's degree"],
["Less then 20.000 EUR"],
["Single"],
["Netherlands", "Netherlands"],
["1399"],
["Prolific Participant"],
["English", "Dutch", "German"],
["Operations", "Unemployed"],
["None"],
["None"],
["Health & Beauty", "Clothing & Shoes", "Books", "None"],
["Whatsapp", "Youtube", "Instagram", "None"],
[
"TV (Local/Cable News Broadcast)",
"TV (Late Night Comedy, Other)",
"Radio (AM/FM, Internet, Satellite)",
"Print (Newspapers & Periodicals)",
"None",
],
],
],
},
],
};
I am transforming it to the following shape with a function I have:
const sample = [
{
name: "123ilSE",
longitude: 5.1193,
latitude: 52.3246,
agreeableness: 0.147083333333333,
openness: 0.211041666666667,
neuroticism: 0.168833333333333,
extraversion: 0.150291666666666,
conscientiousness: 0.187041666666666,
angry: 0.0441711768507957,
fear: 0.020498564466834,
joy: 0.875858068466186,
sadness: 0.0477884039282798,
love: 0.00839435961097478,
country: "Netherlands",
question1: ["Right"],
question2: ["Student Loan", "None"],
question3: ["Not at all, i’d rather rent all assets."],
question4: ["Another benefit"],
question5: ["Every two weeks", "Yearly a few times"],
question6: [
"None",
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
question7: ["Two to Three Times a Week"],
question8: [
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
question9: [
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
question10: [
"None",
"1 to 2 hours",
"1 to 2 hours",
"3 hours or more",
"Less then 1 hour",
],
question11: ["Every two weeks", "Yearly a few times"],
question12: ["Two to Three Times a Week"],
question13: ["Every Year"],
question14: ["Banking & Financial Services", "Unemployed"],
question15: ["I don't have a car"],
question16: ["Netherlands", "Netherlands"],
question17: ["3 - 4 persons"],
question18: ["Maybe, it depends if nothing betters comes up"],
question19: ["Desktop"],
question20: [],
question21: ["I don't drive or have a car"],
question22: [
"E, I can be found on social media platforms and maintain my profile but do little else.",
],
question23: ["None", "Healthcare Insurance"],
question24: ["None", "Hockey", "Hiking"],
question25: ["Hiking"],
question26: ["Unemployed"],
question27: ["1999-09-20 00:00:00"],
question28: ["Female"],
question29: ["Bachelor's degree"],
question30: ["Less then 20.000 EUR"],
question31: ["Single"],
question32: ["Netherlands", "Netherlands"],
question33: ["1399"],
question34: ["Prolific Participant"],
question35: ["English", "Dutch", "German"],
question36: ["Operations", "Unemployed"],
question37: ["None"],
question38: ["None"],
question39: ["Health & Beauty", "Clothing & Shoes", "Books", "None"],
question40: ["Whatsapp", "Youtube", "Instagram", "None"],
question41: [
"TV (Local/Cable News Broadcast)",
"TV (Late Night Comedy, Other)",
"Radio (AM/FM, Internet, Satellite)",
"Print (Newspapers & Periodicals)",
"None",
],
},
];
This is the function computeData which I used to map over the array and then apply reduce() twice in order to get the object in the format I need. filters is an array which contains the keys of the final object. I am aware this is not the most efficient manner to do so, therefore I need help with improving this and not using reduce() twice in function computeData.
const filters = [
"name",
"longitude",
"latitude",
"agreeableness",
"openness",
"neuroticism",
"extraversion",
"conscientiousness",
"angry",
"fear",
"joy",
"sadness",
"love",
"country",
"question1",
"question2",
"question3",
"question4",
"question5",
"question6",
"question7",
"question8",
"question9",
"question10",
"question11",
"question12",
"question13",
"question14",
"question15",
"question16",
"question17",
"question18",
"question19",
"question20",
"question21",
"question22",
"question23",
"question24",
"question25",
"question26",
"question27",
"question28",
"question29",
"question30",
"question31",
"question32",
"question33",
"question34",
"question35",
"question36",
"question37",
"question38",
"question39",
"question40",
"question41",
];
const computeData = ({ records } = {}) => {
return (
records &&
records.map(({ _fields }) => {
const screenName = _fields[0];
const country = _fields[2][0];
const userPersonality = filters.reduce((acc, curr, idx) => {
if (idx === 0) {
acc[curr] = screenName;
} else if (idx >= 1 && idx <= 12) {
acc[curr] = parseFloat(_fields[1][idx - 1]);
} else if (idx === 13) {
acc[curr] = country;
}
return acc;
}, {});
const questions = _fields[3];
const finalResults = filters.reduce((acc, curr, idx) => {
if (idx > 13) {
questions[idx - 14]
? (acc[curr] = questions[idx - 14])
: (acc[curr] = []);
}
return acc;
}, userPersonality);
return finalResults;
})
);
};
Given the array of responses, you can map them to an array of entries for the new object by using the index parameter in .map and concatenating with 'question'. Then pass the result to Object.fromEntries.
The other properties like "Longitude:5.1193" can be split on : and also be passed to Object.fromEntries.
const result={records:[{keys:["names","value","country","questions"],length:4,_fields:["123ilSE",["Longitude:5.1193","Latitude:52.3246","Agreeableness:0.147083333333333","Openness:0.211041666666667","Neuroticism:0.168833333333333","Extraversion:0.150291666666666","Conscientiousness:0.187041666666666","Angry:0.0441711768507957","Fear:0.020498564466834","Joy:0.875858068466186","Sadness:0.0477884039282798","Love:0.00839435961097478"],["Netherlands","Netherlands"],[["Right"],["Student Loan","None"],["Not at all, i’d rather rent all assets."],["Another benefit"],["Every two weeks","Yearly a few times"],["None","1 to 2 hours","1 to 2 hours","3 hours or more","Less then 1 hour"],["Two to Three Times a Week"],["1 to 2 hours","1 to 2 hours","3 hours or more","Less then 1 hour"],["1 to 2 hours","1 to 2 hours","3 hours or more","Less then 1 hour"],["None","1 to 2 hours","1 to 2 hours","3 hours or more","Less then 1 hour"],["Every two weeks","Yearly a few times"],["Two to Three Times a Week"],["Every Year"],["Banking & Financial Services","Unemployed"],["I don't have a car"],["Netherlands","Netherlands"],["3 - 4 persons"],["Maybe, it depends if nothing betters comes up"],["Desktop"],[],["I don't drive or have a car"],["E, I can be found on social media platforms and maintain my profile but do little else."],["None","Healthcare Insurance"],["None","Hockey","Hiking"],["Hiking"],["Unemployed"],["1999-09-20 00:00:00"],["Female"],["Bachelor's degree"],["Less then 20.000 EUR"],["Single"],["Netherlands","Netherlands"],["1399"],["Prolific Participant"],["English","Dutch","German"],["Operations","Unemployed"],["None"],["None"],["Health & Beauty","Clothing & Shoes","Books","None"],["Whatsapp","Youtube","Instagram","None"],["TV (Local/Cable News Broadcast)","TV (Late Night Comedy, Other)","Radio (AM/FM, Internet, Satellite)","Print (Newspapers & Periodicals)","None"]]]}]};
const [name, otherProps, [country], responsesArr] = result.records[0]._fields;
const output = {
name,
...Object.fromEntries(otherProps.map(str => {
const [key, val] = str.split(':');
return [key, Number(val)];
})),
country,
...Object.fromEntries(responsesArr.map(
(responses, i) => ['question' + (i + 1), responses]
))
};
console.log(output);
I have an array blackList where I store blacklisted business names, now I have a results array of objects with many business, I want to store in an array the business names which are not included in the blackListed array, what is the easier and most performant way to do this?
Is a nested loop really needed for this?
blackList = [ "Dominos Pizza", "Domino's Pizza", "McDonald's", "McDonalds", "Telepizza", "Subway", "Burger King", "KFC", "Pans&Co", "Pans&Company" ,
"Rodilla", "Rodilla Campamento", "Granier", "Llaollao" , "Taco Bell", "Wendy's", "Dunkin' Donuts", "Pizza Hut", "Papa John's Pizza", "Little Caesars",
"Panera Bread", "Chipotle", "Papa Murphy's", "Hungry Howie", "Chipotle Mexican Grill", "Starbucks"],
list = [ { name:'business 1' }, { name:'business 2' }, { name:'business 3' } ]
The easiest way to do this is to use filter and destructuring:
const blackList = ["Dominos Pizza", "Domino's Pizza", "McDonald's", "McDonalds", "Telepizza", "Subway", "Burger King", "KFC", "Pans&Co", "Pans&Company",
"Rodilla", "Rodilla Campamento", "Granier", "Llaollao", "Taco Bell", "Wendy's", "Dunkin' Donuts", "Pizza Hut", "Papa John's Pizza", "Little Caesars",
"Panera Bread", "Chipotle", "Papa Murphy's", "Hungry Howie", "Chipotle Mexican Grill", "Starbucks"
];
const list = [{
name: 'business 1'
}, {
name: 'business 2'
}, {
name: 'business 3'
}, {
name: "Granier"
}];
const notOnBlacklist = list.filter(({ name }) => !blackList.includes(name));
console.log(notOnBlacklist);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Try
let blackList =
{"Dominos Pizza":1, "Domino's Pizza":1, "McDonald's":1, "McDonalds":1
,"Telepizza":1, "Subway":1, "Burger King":1, "KFC":1, "Pans&Co":1
,"Pans&Company":1, "Rodilla":1, "Rodilla Campamento":1, "Granier":1
,"Llaollao":1, "Taco Bell":1, "Wendy's":1, "Dunkin' Donuts":1, "Pizza Hut":1
,"Papa John's Pizza":1, "Little Caesars":1, "Panera Bread":1, "Chipotle":1
,"Papa Murphy's":1, "Hungry Howie":1, "Chipotle Mexican Grill":1
,"Starbucks":1 };
let list = [];
addBusiness("'business 1'");
addBusiness("Domino's Pizza");
addBusiness("'business 2'");
addBusiness("Hungry Howie");
addBusiness("'business 3'");
console.log(list);
function addBusiness (name) {
if (blackList.hasOwnProperty(name)) return;
list.push({'name':name});
}
I'm working on a website where you can search for music. I want to put a filter option where people can filter on minimum age.
This is my JSON file:
{
"artists":[
{
"name": "Martin Garrix",
"origin": "Netherlands",
"age": "22 years old",
"artist_id": "c0dc129d8a886a2c9bf487b826c3614a6630fb9c",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/98081145&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "Armin van Buuren",
"origin": "Netherlands",
"age": "41 years old",
"artist_id": "8b0a178ce06055312456cccc0c9aa7679d8054f1",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/181749728&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "Don Diablo",
"origin": "Netherlands",
"age": "38 years old",
"artist_id": "178c6e7e3bf24710d4895048586a86f1bb81d842",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/212802517&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "David Guetta",
"origin": "France",
"age": "50 years old",
"artist_id": "c2714423228a8012ad37af0186447cbb7ff589f7",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/140006470&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
},
{
"name": "Alesso",
"origin": "Sweden",
"age": "26 years old",
"artist_id": "69fa09f6e181093fe0ea2ce1a4099066509f7837",
"best_song":"https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/288914798&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true"
}
]
}
And this is my HTML:
<div class = "div-age">
<label for="age-select">Minimum age</label>
<input type="text" class = "search-age">
</div>
So for example; If you put 40 in the input field, you only get "Armin van Buuren" and "David Guetta".
This is what I have right now.
document.querySelector(`.search-age`).addEventListener(`keyup` , e => {
const term = e.target.value.toLowerCase();
const ageList = document.getElementsByClassName(`artist-info`);
Array.from(ageList).forEach(function(ageList) {
const artistAge = ageList.querySelector(`.age`).textContent;
if (artistAge.toLowerCase().includes(term)) {
ageList.style.display = `flex`;
} else {
ageList.style.display = `none`;
}
})
});
The problem I have now, is that it only filter the exact number. So for example, I put 22, I only get "Martin Garrix"
with filter(), you can do the following way:
const input = {
artists: [
{
name: 'Martin Garrix',
origin: 'Netherlands',
age: '22 years old',
artist_id: 'c0dc129d8a886a2c9bf487b826c3614a6630fb9c',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/98081145&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'Armin van Buuren',
origin: 'Netherlands',
age: '41 years old',
artist_id: '8b0a178ce06055312456cccc0c9aa7679d8054f1',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/181749728&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'Don Diablo',
origin: 'Netherlands',
age: '38 years old',
artist_id: '178c6e7e3bf24710d4895048586a86f1bb81d842',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/212802517&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'David Guetta',
origin: 'France',
age: '50 years old',
artist_id: 'c2714423228a8012ad37af0186447cbb7ff589f7',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/140006470&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
{
name: 'Alesso',
origin: 'Sweden',
age: '26 years old',
artist_id: '69fa09f6e181093fe0ea2ce1a4099066509f7837',
best_song:
'https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/288914798&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true',
},
],
};
const minAge = 40;
const output = input.artists.filter(cur => minAge < parseInt(cur.age));
console.log(output);
You may try to convert the age string to corresponding number using parseInt and then compare it to the value:
// Convert term and artist's age to corresponding integers
term = parseInt(term, 10);
artistAge = parseInt(artistAge, 10);
if (artistAge >= term) {
ageList.style.display = `flex`;
} else {
// ...
}
A couple of things:
you don't need Template literals, you can just use plain string.
Don't use keyup, use input instead as event for such things: it also get things if the user paste the value using a different device than keyboard – e.g. mouse.
Don't use getElementsByClassName since it returns a live HTMLCollection. Use querySelectorAll instead, that returns a static NodeList. It also supports forEach directly, so you don't need to use Array.from.
Don't shadowing the variable, as ageList in the code you wrote, for example: it can lead to unexpected bugs.
Said that:
// you might not want to query all the time this list,
// every time the user change the input value.
const ageList = document.querySelectorAll('.artist-info');
document.querySelector('.search-age').addEventListener('input' , e => {
// no need to lowercase, it's numeric.
// you might want to add some check or constraint on
// <input> validation
const term = +e.target.value;
ageList.forEach(node => {
const artistAge = node.querySelector('.age').textContent;
node.style.display = parseInt(artistAge, 10) >= term ? 'flex' : 'none';
})
});