I need to write a conditional that checked each image value and if its empty displays a stock photo 'selfie.jpg' and if it is not then display whatever is inside of it.
I know how to access it beat.officers[0].image. what I don't know is how to make the program check through the length of officers for each items image value, check if its empty and then display a photo based on the results of that check.
pls help its for a test.
A image of the Json object I am trying to work with
const policeData = [
{
beat:
{
name: 'Portishead',
latLong: ' ',
introText: 'Contact your local policing team, find opportunities to meet the team and view or contribute to community policing priorities for your area.',
officers: [
{
name: 'Trevor Dyson',
role: 'Neighbourhood Police Team Sergeant',
image: ''
},
{
name: 'Kirsten Karcher',
role: 'Police Community Support Officer',
image: 'kkarcher.jpg'
},
{
name: 'Bill Hoover',
role: 'Police Community Support Officer',
image: ''
},
{
name: 'Andrew Henry',
role: 'Partnership Support Officer',
image: ''
}
],
priorities: [
{
title: 'Road Safety Week',
updated: '18 November 2019',
path: '/road-safety-week/'
},
{
title: 'Community SpeedWatch',
updated: '14 August 2019',
path: '/community-speedwatch/'
},
{
title: 'Mopeds using footpaths and speeding vehicles',
updated: '04 September 2019',
path: '/mopeds-using-footpaths-and-speeding-vehicles/'
}
]
}
}];
So here is my template which is functional. As you can see though its not dynamic and I tried to input the conditional as a function with an if statement but its just not working. I did consider trying the turnery (condition : if yes : if no) but I struggled with that too.
Some of the image values are empty you see? Ultimately, I am trying to make it go through each object and check its image value and then run the conditional.
function kk(police) {
officers = police.beat.officers.length;
return `
<div class=person>
<img class="pol-photo" src = "${photoO(police.beat.officers[0])}"
<h2 class ="pol-name">${police.beat.officers[1].name}</h2>
<p> ${police.beat.officers[1].role}</p>
</div>
`
}
function photoO(pol) {
if (pol == '' ) {
return 'officer-profile.jpg'
} else {
return 'kkarcher.jpg'
}
}
You can use the functions from below to get the correct output. One function will return the HTML for just one officer while the other will return the HTML of all of them. You can test it below.
const policeData = [
{
beat:
{
name: 'Portishead',
latLong: ' ',
introText: 'Contact your local policing team, find opportunities to meet the team and view or contribute to community policing priorities for your area.',
officers: [
{
name: 'Trevor Dyson',
role: 'Neighbourhood Police Team Sergeant',
image: ''
},
{
name: 'Kirsten Karcher',
role: 'Police Community Support Officer',
image: 'kkarcher.jpg'
},
{
name: 'Bill Hoover',
role: 'Police Community Support Officer',
image: ''
},
{
name: 'Andrew Henry',
role: 'Partnership Support Officer',
image: ''
}
],
priorities: [
{
title: 'Road Safety Week',
updated: '18 November 2019',
path: '/road-safety-week/'
},
{
title: 'Community SpeedWatch',
updated: '14 August 2019',
path: '/community-speedwatch/'
},
{
title: 'Mopeds using footpaths and speeding vehicles',
updated: '04 September 2019',
path: '/mopeds-using-footpaths-and-speeding-vehicles/'
}
]
}
}];
// helper function to check if value is empty
function existsAndNotEmpty(value) {
if (typeof value != 'undefined' && value.length > 0) {
return true;
}
return false;
}
function getOfficerHTML(officer) {
let result = "";
if( existsAndNotEmpty(officer.image) ) {
result += '<img class="pol-photo" src = "' + officer.image + '" />';
} else {
result += '<img class="pol-photo" src = "officer-profile.jpg" />';
}
if( existsAndNotEmpty(officer.name) ) {
result += '<h2 class ="pol-name">' + officer.name + '</h2>';
} else {
result += '<h2 class ="pol-name">Unknown officer</h2>';
}
if( existsAndNotEmpty(officer.role) ) {
result += '<p>' + officer.role + '</p>';
} else {
result += '<p>Unknown role</p>';
}
return result;
}
function getAllOfficerHTML() {
let result = "";
let officerLength = policeData[0].beat.officers.length;
let officers = policeData[0].beat.officers;
for(var i=0; i < officerLength; i++){
result += getOfficerHTML(officers[i]);
}
return result;
}
// Now you can use it like this to print a single officer
var singleOfficer = getOfficerHTML(policeData[0].beat.officers[1]);
console.log(singleOfficer);
// or like this to get all ooficers at once
var allOfficers = getAllOfficerHTML();
console.log(allOfficers);
As the title says, I'm trying to count groups of data within groups of data: My logic is to group all the data into states, then group date into years. so that the output should look like something like:
state,year,count
mo,1910,2
in,1910,1
il,1910,3
or,1910,4
co,1910,2
nd,1910,1
...
mo,1911,5
in,1911,4
il,1911,6
or,1911,2
co,1911,8
The CSV I'm using has a lot more columns that needed, I'm only interested in the columns state and year. My code below isn't working, any help would be great.
const countStates = filteredData.reduce((m, d) => {
if(!m[d.year]){
m[d.year] = {...d, count: 1};
return m;
}
m[d.state];
m[d.year];
m[d.year].count += 1;
return m;
},{});
const countedStates = Object.keys(countStates).map((k) => {
const item = countStates[k];
return {
state: item.state,
year: item.year,
count: item.count
}
})
Edit
Example of the dataset I'm using:
datetime,city,state,country,shape,duration (seconds),duration (hours/min),comments,date posted,latitude,longitude
10/10/1949 20:30,san marcos,tx,us,cylinder,2700,45 minutes,"This event took place in early fall around 1949-50. It occurred after a Boy Scout meeting in the Baptist Church. The Baptist Church sit",4/27/2004,29.8830556,-97.9411111
10/10/1949 21:00,lackland afb,tx,,light,7200,1-2 hrs,"1949 Lackland AFB, TX. Lights racing across the sky & making 90 degree turns on a dime.",12/16/2005,29.38421,-98.581082
10/10/1955 17:00,chester (uk/england),,gb,circle,20,20 seconds,"Green/Orange circular disc over Chester, England",1/21/2008,53.2,-2.916667
10/10/1956 21:00,edna,tx,us,circle,20,1/2 hour,"My older brother and twin sister were leaving the only Edna theater at about 9 PM,...we had our bikes and I took a different route home",1/17/2004,28.9783333,-96.6458333
10/10/1960 20:00,kaneohe,hi,us,light,900,15 minutes,"AS a Marine 1st Lt. flying an FJ4B fighter/attack aircraft on a solo night exercise, I was at 50ꯠ' in a "clean" aircraft (no ordinan",1/22/2004,21.4180556,-157.8036111
10/10/1961 19:00,bristol,tn,us,sphere,300,5 minutes,"My father is now 89 my brother 52 the girl with us now 51 myself 49 and the other fellow which worked with my father if he's still livi",4/27/2007,36.5950000,-82.1888889
10/10/1965 21:00,penarth (uk/wales),,gb,circle,180,about 3 mins,"penarth uk circle 3mins stayed 30ft above me for 3 mins slowly moved of and then with the blink of the eye the speed was unreal",2/14/2006,51.434722,-3.18
10/10/1965 23:45,norwalk,ct,us,disk,1200,20 minutes,"A bright orange color changing to reddish color disk/saucer was observed hovering above power transmission lines.",10/2/1999,41.1175000,-73.4083333
10/10/1966 20:00,pell city,al,us,disk,180,3 minutes,"Strobe Lighted disk shape object observed close, at low speeds, and low altitude in Oct 1966 in Pell City Alabama",3/19/2009,33.5861111,-86.2861111
10/10/1966 21:00,live oak,fl,us,disk,120,several minutes,"Saucer zaps energy from powerline as my pregnant mother receives mental signals not to pass info",5/11/2005,30.2947222,-82.9841667
10/10/1968 13:00,hawthorne,ca,us,circle,300,5 min.,"ROUND , ORANGE , WITH WHAT I WOULD SAY WAS POLISHED METAL OF SOME KIND AROUND THE EDGES .",10/31/2003,33.9163889,-118.3516667
10/10/1968 19:00,brevard,nc,us,fireball,180,3 minutes,"silent red /orange mass of energy floated by three of us in western North Carolina in the 60s",6/12/2008,35.2333333,-82.7344444
10/10/1970 16:00,bellmore,ny,us,disk,1800,30 min.,"silver disc seen by family and neighbors",5/11/2000,40.6686111,-73.5275000
And the code I used to filter out the data:
fs.createReadStream('./data/scrubbed.csv')
.pipe(readCSV())
.on('data', (data) => CSV.push(data))
.on('end', () => {
let data = CSV.map((d) => {
return {
year: new Date (d.datetime).getFullYear(),
state: d.state,
country: d.country
}
});
filteredData = data.filter((d) => {
return d.state !== "" && d.country === "us"
})
Which returns this (an example of the dataset):
[ { year: 1949, state: 'tx', country: 'us' },
{ year: 1956, state: 'tx', country: 'us' },
{ year: 1960, state: 'hi', country: 'us' },
{ year: 1961, state: 'tn', country: 'us' },
{ year: 1965, state: 'ct', country: 'us' }...
The above is what I'm trying to group twice using reduce
The below code gets an array of states with the year and using reduce we are getting the count of each state grouped by year as
var data = [
{ year: '1910', state: 'mo', country: 'us' },
{ year: '1910', state: 'in', country: 'us' },
{ year: '1910', state: 'il', country: 'us' },
{ year: '1910', state: 'mo', country: 'us' },
{ year: '1911', state: 'in', country: 'us' },
{ year: '1911', state: 'il', country: 'us' },
{ year: '1911', state: 'mo', country: 'us' },
{ year: '1911', state: 'in', country: 'us' }
];
var organizedData = data.reduce((acc, val, index) => {
acc[val.state] = acc[val.state] || {};
acc[val.state][val.year] = (+acc[val.state][val.year] || 0) + 1;
return acc;
}, {});
console.log(organizedData);
There are 52 weeks in a year, If i manually group 13 weeks into one quarter, it will give me a wrong result in high charts. Sometimes 13th week will be in 2nd quarter,so is there any function which will group weeks into quarter ?
Iam gettting data in following format:
Response is an object,consists of quarterNumber, actual production and planned production and weekwisedata, which is a list consists of weeknumber and weekly planned production and weekly actual production.
{"response":[{"quarterNumber":"1","actualQuarterProduction":"1.5","plannedQuarterProduction":"13.49","weekwisedata":[{"quarterNumber":1,"weekNumber":"1","weeklyPlannedProduction":"0","weeklyActualProduction":"0"}, {"quarterNumber":1,"weekNumber":"2","weeklyPlannedProduction":"13.49","weeklyActualProduction":"0"}, {"quarterNumber":1,"weekNumber":"3","weeklyPlannedProduction":"0","weeklyActualProduction":"0"},
{"quarterNumber":"2","actualQuarterProduction":"211.18","plannedQuarterProduction":"850",
"weekwisedata":[{"quarterNumber":2,"weekNumber":"14","weeklyPlannedProduction":"67.45","weeklyActualProduction":"0"},{"quarterNumber":2,"weekNumber":"15","weeklyPlannedProduction":"67.45","weeklyActualProduction":"0"},{"quarterNumber":2,"weekNumber":"16","weeklyPlannedProduction":"67.45","weeklyActualProduction":"0"},{"quarterNumber":2,"weekNumber":"17","weeklyPlannedProduction":"53.96","weeklActualProduction":"0"},{"quarterNumber":2,"weekNumber":"18","weeklyPlannedProduction":"67.45","weeklyActualProduction":"46.45"}]}
In Highchart iam displayng the data manually as shown below:
function(dataVal){
drilldown: {
series: [{
id: 'Quarter1a',
name: 'Actual Quality ',
data: [{
name: 'Week1',
y:parseFloat(dataVal.response[0].weekwisedata[0].weeklyActualProduction)
},
{
name: 'Week2',
y:parseFloat(dataVal.response[0].weekwisedata[1].weeklyActualProduction)
}
]
},
{
id: 'Quarter1p',
name: 'Planned Quantity',
data: [{
name: 'Week1',
y:parseFloat(dataVal.response[0].weekwisedata[0].weeklyPlannedProduction)
},
{
name: 'Week2',
y:parseFloat(dataVal.response[0].weekwisedata[1].weeklyPlannedProduction)
},
{
name: 'Week3',
y:parseFloat(dataVal.response[0].weekwisedata[2].weeklyPlannedProduction)
}
]
} ]
}
As you can see the above code,manually iam setting week number and values. iam grouping 13 weeks into quarter. can it be automated based on year?
I have an array with lots of games that have unique id. I need to make a request for every id to retrieve minutes played for that specific game.
So my array looks something like this:
[
{
id: 1,
name: 'Team 1 vs Team 2'
},
{
id: 2,
name: 'Team 1 vs Team 2'
},
{
id: 3,
name: 'Team 1 vs Team 2'
},
{
id: 4,
name: 'Team 1 vs Team 2'
},
{
id: 5,
name: 'Team 1 vs Team 2'
}
]
I have been trying to forEach through the array, make a request with Axios to the API and then retrieve the data.
The Api looks like this. It is alot more, just narrowed it down. there is an image below with more description:
{
event: {
123123: {
id: 1,
elapsed: {
1: {
elapsed: '45'
}
}
}
}
The elapsed key is unique, for some reason, so I am using a Object.keys to "find" it.
My code:
array.forEach(game => {
axios.get(`http://example.com/${game.id}`)
.then(res => {
let time = 0;
Object.keys(res.data.event).map(eventId) => { //the eventId is the id for the event, in this case 123123.
Object.keys(res.data.event[eventId].elapsed).map(el => {
time = res.data.event[eventId].elapsed[el].elapsed; //el is the key-id for the elapsed object.
)};
)};
return time;
});
});
This does not work, I just get undefined. What am I doing wrong? And yes, the API looks like a mess. I have images below in case that will help you. It's a JSON file, I just have a JSON Formatter:
EDIT: Edited my code