Related
I'm looking to count the number of times a crime has occurred on a street by counting the times the street is mentioned in a police statistics site then display it.
The display bit I can do, rather it's pulling the count into a variable that I'm struggling to understand where to start.
The data is: https://data.police.uk/api/crimes-street/all-crime?lat=51.728395&lng=-1.2314066
Here's an example of doing it:
fetch(
"https://data.police.uk/api/crimes-street/all-crime?lat=51.728395&lng=-1.2314066"
).then(async (data) => {
const records = await data.json();
// If you'd like to filter records for streets with specific name
const filterByStreetName = (streetName, records) => {
return records.reduce(function (filtered, record) {
if (record.location.street.name.includes(streetName)) {
filtered.push(record);
}
return filtered;
}, []);
};
const elmTreeStreetRecords = filterByStreetName("Elm Tree", records);
console.log(elmTreeStreets);
// Get all street names
const allStreets = records.map((x) => x.location.street.name);
// if you would prefer using ids instead of street names (probably better idea), just change used object property
// const allStreets = records.map((x) => x.location.street.id);
// // Use reduce to create object with street name and count in format streetName:Count
const streetsWithCount = allStreets.reduce((accumulator, value) => {
return { ...accumulator, [value]: (accumulator[value] || 0) + 1 };
}, {});
// if you need to sort them
const sortableStreetNames = Object.entries(streetsWithCount);
const sortedStreetsByCountInDescendingOrder = sortableStreetNames.sort(
([, a], [, b]) => b - a
);
console.log("streetsWithCount", streetsWithCount);
// => {On or near Elm Tree Close: 5, On or near Champion Way: 2}
console.log("allStreets", allStreets);
// => ["On or near Elm Tree Close", "On or near Sports/recreation Area", "On or near Champion Way", "On or near Oxford Road", "On or near Parking Area", "On or near Pedestrian Subway", "On or near Newman Road", "On or near Constance Norman Way", "On or near Catherine Street", "On or near Littlehay Road", …]
console.log("sortedStreetsByCount", sortedStreetsByCountInDescendingOrder);
// => [["On or near Parking Area", 49], ["On or near Supermarket", 29]]
});
It is a pure data from an API, which is not ideal "on or near Parking Area", you didn't specify format, but it is a good place to start, maybe API has some better querying options, maybe you could just filter out some results, or format returned results in a way you want to display them.
You can use Array#reduce to count the occurences given the street ID:
// return a promise to simplify everything
async function streetCount(streetId) {
let response = await fetch("https://data.police.uk/api/crimes-street/all-crime?lat=51.728395&lng=-1.2314066");
let data = await response.json();
// create a counter
return data.reduce((prev, cur) =>
prev + +(cur?.location?.street?.id === streetId), 0); // add the previous count to whether the street ID matches the provided one
// we cast the boolean to a number, so if it's true it'll give 1 (add 1 to the counter) and otherwise 0
// optional chaining is used in case the API provides malformed data; code will still work if removed
}
streetCount(1203542).then(count => {
console.log("Crime occurences:", count);
});
that's it, folks
const allCrimes = [{
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.723879", "street": { "id": 1203542, "name": "On or near Elm Tree Close" }, "longitude": "-1.221349" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102646934, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.725988", "street": { "id": 1203518, "name": "On or near Sports\/recreation Area" }, "longitude": "-1.211410" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647063, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.723362", "street": { "id": 1203546, "name": "On or near Champion Way" }, "longitude": "-1.219389" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102646887, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.725683", "street": { "id": 1203528, "name": "On or near Oxford Road" }, "longitude": "-1.223634" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647032, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.733223", "street": { "id": 1204183, "name": "On or near Parking Area" }, "longitude": "-1.217713" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647491, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.724270", "street": { "id": 1203378, "name": "On or near Pedestrian Subway" }, "longitude": "-1.224730" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647022, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.725454", "street": { "id": 1203529, "name": "On or near Newman Road" }, "longitude": "-1.221684" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647008, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.724505", "street": { "id": 1203430, "name": "On or near Constance Norman Way" }, "longitude": "-1.231762" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647006, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.741460", "street": { "id": 1204314, "name": "On or near Catherine Street" }, "longitude": "-1.232879" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647957, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.736008", "street": { "id": 1204151, "name": "On or near Littlehay Road" }, "longitude": "-1.220069" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647691, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.735840", "street": { "id": 1204256, "name": "On or near Weirs Lane" }, "longitude": "-1.241070" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647682, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.730241", "street": { "id": 1204163, "name": "On or near The Grates" }, "longitude": "-1.216823" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647298, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.733223", "street": { "id": 1204183, "name": "On or near Parking Area" }, "longitude": "-1.217713" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647489, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.733223", "street": { "id": 1204183, "name": "On or near Parking Area" }, "longitude": "-1.217713" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647488, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.728327", "street": { "id": 1203508, "name": "On or near Bartholomew Road" }, "longitude": "-1.214294" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647262, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.734466", "street": { "id": 1204251, "name": "On or near Police Station" }, "longitude": "-1.213898" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647566, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.723879", "street": { "id": 1203542, "name": "On or near Elm Tree Close" }, "longitude": "-1.221349" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102646925, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.737846", "street": { "id": 1204282, "name": "On or near Swinburne Road" }, "longitude": "-1.238342" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647752, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.737395", "street": { "id": 1204202, "name": "On or near Owens Way" }, "longitude": "-1.216236" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647776, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.726360", "street": { "id": 1203426, "name": "On or near Court Place Gardens" }, "longitude": "-1.237783" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647072, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.722292", "street": { "id": 1203460, "name": "On or near Spring Lane" }, "longitude": "-1.211242" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102646796, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.734236", "street": { "id": 1204200, "name": "On or near Oxford Road" }, "longitude": "-1.211889" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647589, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.731954", "street": { "id": 1204211, "name": "On or near Knolles Road" }, "longitude": "-1.213463" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647367, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.727149", "street": { "id": 1203509, "name": "On or near Barns Road" }, "longitude": "-1.210275" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647146, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.726360", "street": { "id": 1203426, "name": "On or near Court Place Gardens" }, "longitude": "-1.237783" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647070, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.719306", "street": { "id": 1203470, "name": "On or near Priory Road" }, "longitude": "-1.215246" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102646560, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.724426", "street": { "id": 1203436, "name": "On or near Asquith Road" }, "longitude": "-1.226653" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102646945, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.727149", "street": { "id": 1203509, "name": "On or near Barns Road" }, "longitude": "-1.210275" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647143, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.727149", "street": { "id": 1203509, "name": "On or near Barns Road" }, "longitude": "-1.210275" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647142, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.732969", "street": { "id": 1204378, "name": "On or near Sports\/recreation Area" }, "longitude": "-1.250385" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647439, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.732987", "street": { "id": 1204240, "name": "On or near Petrol Station" }, "longitude": "-1.214676" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647449, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.731954", "street": { "id": 1204211, "name": "On or near Knolles Road" }, "longitude": "-1.213463" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647353, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.738885", "street": { "id": 1204288, "name": "On or near Quartermain Close" }, "longitude": "-1.233618" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647855, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.730911", "street": { "id": 1204272, "name": "On or near Egerton Road" }, "longitude": "-1.228367" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647349, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.732987", "street": { "id": 1204240, "name": "On or near Petrol Station" }, "longitude": "-1.214676" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647526, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.737124", "street": { "id": 1204153, "name": "On or near Hendred Street" }, "longitude": "-1.220151" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647743, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.730387", "street": { "id": 1204176, "name": "On or near Boswell Road" }, "longitude": "-1.211637" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647347, "location_subtype": "", "month": "2022-06"
}, {
"category": "anti-social-behaviour", "location_type": "Force", "location": { "latitude": "51.729723", "street": { "id": 1204166, "name": "On or near Littlemore Road" }, "longitude": "-1.218715" }, "context": "", "outcome_status": null, "persistent_id": "", "id": 102647291, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.724779", "street": { "id": 1203481, "name": "On or near Long Lane" }, "longitude": "-1.217453" }, "context": "", "outcome_status": {
"category": "Under investigation", "date": "2022-06"
}, "persistent_id": "3db491eb02f57648df9a2af8f1132772ec6bb8f2def3f947747bf22e65885e2b", "id": 102646899, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.732294", "street": { "id": 1204236, "name": "On or near Banjo Road" }, "longitude": "-1.217150" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "f254759e21c52428736f04bbac13b4a1ef1652e593c55e8c26499c1e57532b8a", "id": 102647441, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.740796", "street": { "id": 1204143, "name": "On or near Weyman Terrace" }, "longitude": "-1.222000" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "93c63312fb6b04b1f5c2147f0957f90506db1efdf911cc4dd0dedb1ba779c1c7", "id": 102647926, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.737804", "street": { "id": 1204239, "name": "On or near Agnes Court" }, "longitude": "-1.218271" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "6da017672b1e62fdd1e9fe7a3c8f8290554cb1c2197f1d5a32ec3370a2c64b7b", "id": 102647784, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.735523", "street": { "id": 1204199, "name": "On or near Oxford Road" }, "longitude": "-1.215965" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "b8087f61f3ee54a434603fd413351c3786696945f8311ab8fe66c1b3ce1f309b", "id": 102647657, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.735840", "street": { "id": 1204256, "name": "On or near Weirs Lane" }, "longitude": "-1.241070" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "81eb687f2a3e6f7c4bc33e23ba532dc8012ea08594a286a00d45935909dfb9ff", "id": 102647655, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.736008", "street": { "id": 1204151, "name": "On or near Littlehay Road" }, "longitude": "-1.220069" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "4d82424f72981ac1e5e3c9c77d054aa533bc1a96e8239894e3a387d1941327ce", "id": 102647644, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.734466", "street": { "id": 1204251, "name": "On or near Police Station" }, "longitude": "-1.213898" }, "context": "", "outcome_status": {
"category": "Under investigation", "date": "2022-06"
}, "persistent_id": "823cc48203d0ee98a4c3804fbb800f38a1b52f6a0812699860cfc5a273478fe9", "id": 102647619, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.734902", "street": { "id": 1204235, "name": "On or near Bennett Crescent" }, "longitude": "-1.210617" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "9272b4253caac3c49771bab03aa16ac377fc257b266f2624caa4979f20175973", "id": 102647599, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.734236", "street": { "id": 1204200, "name": "On or near Oxford Road" }, "longitude": "-1.211889" }, "context": "", "outcome_status": {
"category": "Unable to prosecute suspect", "date": "2022-06"
}, "persistent_id": "d821df571e79d0ee6c1655a57aebab9cec661651812b8e33ed0b7b729283735a", "id": 102647562, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.733850", "street": { "id": 1204221, "name": "On or near Gerard Place" }, "longitude": "-1.214632" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "08b1894f4389bfe50ccb19e1211b37a35bb201038f3e8de6f1ccff2ff651ab46", "id": 102647549, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.732987", "street": { "id": 1204240, "name": "On or near Petrol Station" }, "longitude": "-1.214676" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "350b18d189f77795e44f6881c2a1d7758c6756c2a0e1bb692d823cff882b0458", "id": 102647525, "location_subtype": "", "month": "2022-06"
}, {
"category": "bicycle-theft", "location_type": "Force", "location": { "latitude": "51.733223", "street": { "id": 1204183, "name": "On or near Parking Area" }, "longitude": "-1.217713" }, "context": "", "outcome_status": {
"category": "Investigation complete; no suspect identified", "date": "2022-06"
}, "persistent_id": "45b956b4552c06ac28c56cb10ba56b13515e97fff894a9072f548469117091ab", "id": 102647520, "location_subtype": "", "month": "2022-06"
}];
/* crimes at specific street */
function getAmountOfCrimesAtStreetId(streetId) {
const crimesAtStreetId = allCrimes.filter(crimeData => crimeData.location.street.id === streetId);
return crimesAtStreetId.length;
}
const amountOfCrimesAtStreet_1204183 = getAmountOfCrimesAtStreetId(1204183);
console.log(amountOfCrimesAtStreet_1204183); // 4
/* crimes on each street */
// get all unique street ids
const allUniqueStreetIds = [...new Set(allCrimes.map(crimeData=>crimeData.location.street.id))];
// create an object to store amounts of crimes on each street
const amountOfCrimesAtStreet = {};
allUniqueStreetIds.forEach(streetId=>{
const streetIdString = String(streetId);
amountOfCrimesAtStreet[streetIdString] = 0;
});
// fill this object with amounts of crimes (incrementing inside the loop)
allCrimes.forEach(crimeData=>{
const streetIdString = String(crimeData.location.street.id);
amountOfCrimesAtStreet[streetIdString]+=1;
});
// the same result
console.log(amountOfCrimesAtStreet["1204183"]); // 4
This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 2 years ago.
Here is one API call I created for an SDK that returns a Javascript object with various fields:
listProjects(company_id) {
return axios.get(BASE_URL + 'projects?company_id=' + company_id, {
headers: {
Authorization: this.access_token
}
})
.then(function (response) {
//console.log(response.data);
const obj = response.data;
var return_obj = { //needs to return data for all the projects not just the first
id: obj[0].id,
name: obj[0].name,
display_name: obj[0].display_name,
address: obj[0].address,
city: obj[0].city,
state_code: obj[0].state_code,
country_code: obj[0].country_code,
zip: obj[0].zip,
latitude: obj[0].latitude,
longitude: obj[0].longitude
};
return return_obj;
})
.catch(function (error) {
console.log(error);
return error;
});
}
The response looks like the following where there could possibly be multiple projects. I'm not sure how I should iterate through without hard coding a fixed length loop and how I should structure my return object accordingly.
[
{
"id": 20789,
"name": "Sandbox Test Project",
"display_name": "1234 - Sandbox Test Project",
"project_number": "1234",
"address": "6309 Carpinteria Avenue",
"city": "Carpinteria",
"state_code": "CA",
"country_code": "US",
"zip": "93013",
"county": "Santa Barbara County",
"time_zone": "US/Pacific",
"latitude": 34.3850438,
"longitude": -119.4908492,
"stage": "None",
"phone": null,
"created_at": "2020-04-03T00:35:03Z",
"updated_at": "2020-04-03T00:45:17Z",
"active": true,
"origin_id": null,
"origin_data": null,
"origin_code": null,
"owners_project_id": null,
"estimated_value": null,
"project_region_id": null,
"project_bid_type_id": null,
"project_owner_type_id": null,
"photo_id": 310560,
"start_date": null,
"completion_date": null,
"total_value": null,
"accounting_project_number": null,
"store_number": null,
"designated_market_area": null,
"company": {
"id": 27669,
"name": "Example Procore App"
}
},
{
"id": 20758,
"name": "Standard Project Template",
"display_name": "Standard Project Template",
"project_number": null,
"address": null,
"city": null,
"state_code": null,
"country_code": null,
"zip": null,
"county": null,
"time_zone": "US/Pacific",
"latitude": null,
"longitude": null,
"stage": "None",
"phone": null,
"created_at": "2020-04-03T00:25:02Z",
"updated_at": "2020-04-03T00:30:01Z",
"active": true,
"origin_id": null,
"origin_data": null,
"origin_code": null,
"owners_project_id": null,
"estimated_value": null,
"project_region_id": null,
"project_bid_type_id": null,
"project_owner_type_id": null,
"photo_id": null,
"start_date": null,
"completion_date": null,
"total_value": null,
"accounting_project_number": null,
"store_number": null,
"designated_market_area": null,
"company": {
"id": 27669,
"name": "Example Procore App"
}
}
]
You could loop through the results
listProjects(company_id) {
return axios.get(BASE_URL + 'projects?company_id=' + company_id, {
headers: {
Authorization: this.access_token
}
})
.then(function (response) {
//console.log(response.data);
//const obj = response.data;
var return_array = [];
for (var i=0; i<response.data.length; i++){ //iterate
var obj = { //construct i-th object
id: response.data[i].id,
name: response.data[i].name,
display_name: response.data[i].display_name,
address: response.data[i].address,
city: response.data[i].city,
state_code: response.data[i].state_code,
country_code: response.data[i].country_code,
zip: response.data[i].zip,
latitude: response.data[i].latitude,
longitude: response.data[i].longitude
};
return_array.push(obj); //push object to array
}
return return_array; //return array with all the objects
})
.catch(function (error) {
console.log(error);
return error;
});
}
From your code I can see that you are just reassigning the value with the same key names. So instead of returning return return_obj; Why dont you simply return obj[0]; Which already have key value pairs.
Description
You are looking for a for loop or a forEach loop on response.data.forEach(element => { //loop code }); if using a for loop you'd want to use for (let i = 0; i < response.data.length; i++) { //loop over response.data[i] }
Examples
for loop
let data = [
{
"id": 20789,
"name": "Sandbox Test Project",
"display_name": "1234 - Sandbox Test Project",
"project_number": "1234",
"address": "6309 Carpinteria Avenue",
"city": "Carpinteria",
"state_code": "CA",
"country_code": "US",
"zip": "93013",
"county": "Santa Barbara County",
"time_zone": "US/Pacific",
"latitude": 34.3850438,
"longitude": -119.4908492,
"stage": "None",
"phone": null,
"created_at": "2020-04-03T00:35:03Z",
"updated_at": "2020-04-03T00:45:17Z",
"active": true,
"origin_id": null,
"origin_data": null,
"origin_code": null,
"owners_project_id": null,
"estimated_value": null,
"project_region_id": null,
"project_bid_type_id": null,
"project_owner_type_id": null,
"photo_id": 310560,
"start_date": null,
"completion_date": null,
"total_value": null,
"accounting_project_number": null,
"store_number": null,
"designated_market_area": null,
"company": {
"id": 27669,
"name": "Example Procore App"
}
},
{
"id": 20758,
"name": "Standard Project Template",
"display_name": "Standard Project Template",
"project_number": null,
"address": null,
"city": null,
"state_code": null,
"country_code": null,
"zip": null,
"county": null,
"time_zone": "US/Pacific",
"latitude": null,
"longitude": null,
"stage": "None",
"phone": null,
"created_at": "2020-04-03T00:25:02Z",
"updated_at": "2020-04-03T00:30:01Z",
"active": true,
"origin_id": null,
"origin_data": null,
"origin_code": null,
"owners_project_id": null,
"estimated_value": null,
"project_region_id": null,
"project_bid_type_id": null,
"project_owner_type_id": null,
"photo_id": null,
"start_date": null,
"completion_date": null,
"total_value": null,
"accounting_project_number": null,
"store_number": null,
"designated_market_area": null,
"company": {
"id": 27669,
"name": "Example Procore App"
}
}
]
for (let i = 0; i < data.length; i++) {
console.log('index', i, data[i]);
}
foreach loop
let data = [
{
"id": 20789,
"name": "Sandbox Test Project",
"display_name": "1234 - Sandbox Test Project",
"project_number": "1234",
"address": "6309 Carpinteria Avenue",
"city": "Carpinteria",
"state_code": "CA",
"country_code": "US",
"zip": "93013",
"county": "Santa Barbara County",
"time_zone": "US/Pacific",
"latitude": 34.3850438,
"longitude": -119.4908492,
"stage": "None",
"phone": null,
"created_at": "2020-04-03T00:35:03Z",
"updated_at": "2020-04-03T00:45:17Z",
"active": true,
"origin_id": null,
"origin_data": null,
"origin_code": null,
"owners_project_id": null,
"estimated_value": null,
"project_region_id": null,
"project_bid_type_id": null,
"project_owner_type_id": null,
"photo_id": 310560,
"start_date": null,
"completion_date": null,
"total_value": null,
"accounting_project_number": null,
"store_number": null,
"designated_market_area": null,
"company": {
"id": 27669,
"name": "Example Procore App"
}
},
{
"id": 20758,
"name": "Standard Project Template",
"display_name": "Standard Project Template",
"project_number": null,
"address": null,
"city": null,
"state_code": null,
"country_code": null,
"zip": null,
"county": null,
"time_zone": "US/Pacific",
"latitude": null,
"longitude": null,
"stage": "None",
"phone": null,
"created_at": "2020-04-03T00:25:02Z",
"updated_at": "2020-04-03T00:30:01Z",
"active": true,
"origin_id": null,
"origin_data": null,
"origin_code": null,
"owners_project_id": null,
"estimated_value": null,
"project_region_id": null,
"project_bid_type_id": null,
"project_owner_type_id": null,
"photo_id": null,
"start_date": null,
"completion_date": null,
"total_value": null,
"accounting_project_number": null,
"store_number": null,
"designated_market_area": null,
"company": {
"id": 27669,
"name": "Example Procore App"
}
}
];
data.forEach(element => {
console.log(element);
});
References
JavaScript Foreach
Array length
I'm trying to output all of the customer id's within my JSON data. I am using ejs as my templating engine. So far I'm only able to succsefully output 1 customer id via:
<p><%= jsonOrderData.orders[0].customer.id %></p>
When I try to loop through each order I get Cannot read property 'id' of undefined
for loop to loop through
<% for (var i = 0; i < jsonOrderData.orders.length; i++) {%>
<p>Customer: <%= jsonOrderData.orders[i].customer.id %></p>
<% }; %>
If I remove the .id after customer the error then goes away. It then outputs
Customer:[object Object] 50 times which is the legth of the json data.
I don't understand why it's not working within the loop when adding .id when it works fine without the loop manually setting the index?
JSON DATA (Cut Down 2 Orders)
{
"orders": [
{
"id": 533078016054,
"email": "email#gmail.com",
"closed_at": null,
"created_at": "2018-08-10T05:03:36+01:00",
"updated_at": "2018-08-10T05:03:37+01:00",
"number": 52,
"note": "",
"token": "f4877048c08eb98180ee5fda34f978bc",
"gateway": "manual",
"test": false,
"total_price": "13.98",
"subtotal_price": "13.98",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "13.98",
"cart_token": null,
"buyer_accepts_marketing": false,
"name": "#MW1052",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "18.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": null,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-10T05:03:36+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1052,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "email#gmail.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/f4877048c08eb98180ee5fda34f978bc/authenticate?key=redacted",
"admin_graphql_api_id": "gid://shopify/Order/redacted",
"line_items": [
{
"id": 1350736445494,
"variant_id": 8725905539126,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss15",
"variant_title": "S / Bottle Green",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Bottle Green",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736445494",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
},
{
"id": 1350736478262,
"variant_id": 8725905440822,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss12",
"variant_title": "S / Heather Grey",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Heather Grey",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736478262",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"billing_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "Jogn Doe",
"country_code": "GB",
"province_code": null
},
"shipping_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "John Doe",
"country_code": "GB",
"province_code": null
},
"fulfillments": [],
"refunds": [],
"customer": {
"id": 556974014518,
"email": "email#gmail.com",
"accepts_marketing": false,
"created_at": "2018-06-26T00:26:55+01:00",
"updated_at": "2018-08-10T05:03:36+01:00",
"first_name": "John",
"last_name": "Doe",
"orders_count": 22,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 533078016054,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "",
"last_order_name": "#MW1052",
"admin_graphql_api_id": "gid://shopify/Customer/556974014518",
"default_address": {
"id": 601657278518,
"customer_id": 556974014518,
"first_name": "John",
"last_name": "Doe",
"company": null,
"address1": "17A Oaklands Business Centre",
"address2": "Elm Grove",
"city": "Worthing",
"province": null,
"country": "United Kingdom",
"zip": "BN11 5LH",
"phone": null,
"name": "John Doe",
"province_code": null,
"country_code": "GB",
"country_name": "United Kingdom",
"default": true
}
}
},
{
"id": 532977778742,
"email": "james#bungeedesign.com",
"closed_at": null,
"created_at": "2018-08-09T22:18:53+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"number": 51,
"note": "",
"token": "a292d75bd7011cf255a1bf236b23d0a5",
"gateway": "manual",
"test": false,
"total_price": "6.99",
"subtotal_price": "6.99",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "6.99",
"cart_token": null,
"buyer_accepts_marketing": true,
"name": "#MW1051",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "9.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": 1327759385,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-09T22:18:53+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1051,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "james#bungeedesign.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/a292d75bd7011cf255a1bf236b23d0a5/authenticate?key=9322877ce6ce34be2feeb127d73d0f89",
"admin_graphql_api_id": "gid://shopify/Order/532977778742",
"line_items": [
{
"id": 1350552453174,
"variant_id": 8725905408054,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss11",
"variant_title": "S / Black",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Black",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350552453174",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"fulfillments": [],
"refunds": [],
"customer": {
"id": 552537620534,
"email": "james#bungeedesign.com",
"accepts_marketing": true,
"created_at": "2018-06-15T10:44:13+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"first_name": "James",
"last_name": "Rogers",
"orders_count": 18,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 532977778742,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "password page, prospect",
"last_order_name": "#MW1051",
"admin_graphql_api_id": "gid://shopify/Customer/552537620534"
}
}
]
}
What you have runs fine. It might be possible that something is getting lost in translation or .id is at another level. My guess is that you are not setting the variable jsonOrderData as you are expecting.
If you do console.log(jsonOrderData); do you get what you expect?
This works fine:
const json = {
"orders": [
{
"id": 533078016054,
"email": "email#gmail.com",
"closed_at": null,
"created_at": "2018-08-10T05:03:36+01:00",
"updated_at": "2018-08-10T05:03:37+01:00",
"number": 52,
"note": "",
"token": "f4877048c08eb98180ee5fda34f978bc",
"gateway": "manual",
"test": false,
"total_price": "13.98",
"subtotal_price": "13.98",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "13.98",
"cart_token": null,
"buyer_accepts_marketing": false,
"name": "#MW1052",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "18.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": null,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-10T05:03:36+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1052,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "email#gmail.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/f4877048c08eb98180ee5fda34f978bc/authenticate?key=redacted",
"admin_graphql_api_id": "gid://shopify/Order/redacted",
"line_items": [
{
"id": 1350736445494,
"variant_id": 8725905539126,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss15",
"variant_title": "S / Bottle Green",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Bottle Green",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736445494",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
},
{
"id": 1350736478262,
"variant_id": 8725905440822,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss12",
"variant_title": "S / Heather Grey",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Heather Grey",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350736478262",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"billing_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "Jogn Doe",
"country_code": "GB",
"province_code": null
},
"shipping_address": {
"first_name": "John",
"address1": "17A Oaklands Business Centre",
"phone": null,
"city": "Worthing",
"zip": "BN11 5LH",
"province": null,
"country": "United Kingdom",
"last_name": "Doe",
"address2": "Elm Grove",
"company": null,
"latitude": 50.8162744,
"longitude": -0.4010653,
"name": "John Doe",
"country_code": "GB",
"province_code": null
},
"fulfillments": [],
"refunds": [],
"customer": {
"id": 556974014518,
"email": "email#gmail.com",
"accepts_marketing": false,
"created_at": "2018-06-26T00:26:55+01:00",
"updated_at": "2018-08-10T05:03:36+01:00",
"first_name": "John",
"last_name": "Doe",
"orders_count": 22,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 533078016054,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "",
"last_order_name": "#MW1052",
"admin_graphql_api_id": "gid://shopify/Customer/556974014518",
"default_address": {
"id": 601657278518,
"customer_id": 556974014518,
"first_name": "John",
"last_name": "Doe",
"company": null,
"address1": "17A Oaklands Business Centre",
"address2": "Elm Grove",
"city": "Worthing",
"province": null,
"country": "United Kingdom",
"zip": "BN11 5LH",
"phone": null,
"name": "John Doe",
"province_code": null,
"country_code": "GB",
"country_name": "United Kingdom",
"default": true
}
}
},
{
"id": 532977778742,
"email": "james#bungeedesign.com",
"closed_at": null,
"created_at": "2018-08-09T22:18:53+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"number": 51,
"note": "",
"token": "a292d75bd7011cf255a1bf236b23d0a5",
"gateway": "manual",
"test": false,
"total_price": "6.99",
"subtotal_price": "6.99",
"total_weight": 0,
"total_tax": "0.00",
"taxes_included": false,
"currency": "GBP",
"financial_status": "pending",
"confirmed": true,
"total_discounts": "0.00",
"total_line_items_price": "6.99",
"cart_token": null,
"buyer_accepts_marketing": true,
"name": "#MW1051",
"referring_site": null,
"landing_site": null,
"cancelled_at": null,
"cancel_reason": null,
"total_price_usd": "9.00",
"checkout_token": null,
"reference": null,
"user_id": 1706983449,
"location_id": 1327759385,
"source_identifier": null,
"source_url": null,
"processed_at": "2018-08-09T22:18:53+01:00",
"device_id": null,
"phone": null,
"customer_locale": null,
"app_id": 1354745,
"browser_ip": null,
"landing_site_ref": null,
"order_number": 1051,
"discount_applications": [],
"discount_codes": [],
"note_attributes": [],
"payment_gateway_names": [
"manual"
],
"processing_method": "manual",
"checkout_id": null,
"source_name": "shopify_draft_order",
"fulfillment_status": null,
"tax_lines": [],
"tags": "",
"contact_email": "james#bungeedesign.com",
"order_status_url": "https://checkout.shopify.com/1245839385/orders/a292d75bd7011cf255a1bf236b23d0a5/authenticate?key=9322877ce6ce34be2feeb127d73d0f89",
"admin_graphql_api_id": "gid://shopify/Order/532977778742",
"line_items": [
{
"id": 1350552453174,
"variant_id": 8725905408054,
"title": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt",
"quantity": 1,
"price": "6.99",
"sku": "ss11",
"variant_title": "S / Black",
"vendor": "Fruit Of The Loom",
"fulfillment_service": "manual",
"product_id": 719146287158,
"requires_shipping": true,
"taxable": false,
"gift_card": false,
"name": "Fruit of the Loom Poly/Cotton Piqué Polo Shirt - S / Black",
"variant_inventory_management": "shopify",
"properties": [],
"product_exists": true,
"fulfillable_quantity": 1,
"grams": 0,
"total_discount": "0.00",
"fulfillment_status": null,
"discount_allocations": [],
"admin_graphql_api_id": "gid://shopify/LineItem/1350552453174",
"tax_lines": [
{
"title": "VAT",
"price": "0.00",
"rate": 0.2
}
]
}
],
"shipping_lines": [],
"fulfillments": [],
"refunds": [],
"customer": {
"id": 552537620534,
"email": "james#bungeedesign.com",
"accepts_marketing": true,
"created_at": "2018-06-15T10:44:13+01:00",
"updated_at": "2018-08-09T22:18:53+01:00",
"first_name": "James",
"last_name": "Rogers",
"orders_count": 18,
"state": "enabled",
"total_spent": "0.00",
"last_order_id": 532977778742,
"note": null,
"verified_email": true,
"multipass_identifier": null,
"tax_exempt": false,
"phone": null,
"tags": "password page, prospect",
"last_order_name": "#MW1051",
"admin_graphql_api_id": "gid://shopify/Customer/552537620534"
}
}
]
};
for (let i = 0; i < json.orders.length; i++) {
const order = json.orders[i];
console.log(order.customer.id);
}
I have retrieved a JSON object from a public data API which look similar to following.
[
{
"category": "Burglary",
"location_type": "Force",
"location": {
"latitude": "51.497877",
"street": {
"id": 953834,
"name": "On or near Major Road"
},
"longitude": "-0.064175"
},
"context": "",
"outcome_status": null,
"persistent_id": "",
"id": 53832838,
"location_subtype": "",
"month": "2016-12"
},
{
"category": "anti-social-behaviour",
"location_type": "Force",
"location": {
"latitude": "51.497877",
"street": {
"id": 953834,
"name": "On or near Major Road"
},
"longitude": "-0.064175"
},
"context": "",
"outcome_status": null,
"persistent_id": "",
"id": 53832841,
"location_subtype": "",
"month": "2016-12"
},
{
"category": "anti-social-behaviour",
"location_type": "Force",
"location": {
"latitude": "51.497877",
"street": {
"id": 953834,
"name": "On or near Major Road"
},
"longitude": "-0.064175"
},
"context": "",
"outcome_status": null,
"persistent_id": "",
"id": 53832849,
"location_subtype": "",
"month": "2016-12"
},
{
"category": "anti-social-behaviour",
"location_type": "Force",
"location": {
"latitude": "51.500440",
"street": {
"id": 953881,
"name": "On or near Chambers Street"
},
"longitude": "-0.066891"
},
"context": "",
"outcome_status": null,
"persistent_id": "",
"id": 53832881,
"location_subtype": "",
"month": "2016-12"
} ]
I am trying to count how many crimes happened in each category. Is it correct to access category value as 'obj[0].category' ? What would be the best way to count them?
Assuming you've parsed the JSON to get an array of objects, you can use the array .reduce() method to count the categories. .reduce() calls the function that you pass it once for each item in your array, passing as arguments an "accumulator" acc, which in this case will be an object {}, and the current array value crime.
var data = // your data here
var categories = data.reduce(function(acc, crime) {
if (!acc[crime.category]) // if current category not in acc object
acc[crime.category] = 1; // add it to acc with value 1
else // otherwise (it exists), so
acc[crime.category]++; // increment it
return acc;
}, {});
The result will be an object like this:
{
"Burglary": 1,
"anti-social-behaviour": 3
}
...so if you want to know how many burglaries occurred you could say categories["Burglary"].
(Expand and run the following snippet to see it work...)
var data = [
{
"category": "Burglary",
"location_type": "Force",
"location": {
"latitude": "51.497877",
"street": {
"id": 953834,
"name": "On or near Major Road"
},
"longitude": "-0.064175"
},
"context": "",
"outcome_status": null,
"persistent_id": "",
"id": 53832838,
"location_subtype": "",
"month": "2016-12"
},
{
"category": "anti-social-behaviour",
"location_type": "Force",
"location": {
"latitude": "51.497877",
"street": {
"id": 953834,
"name": "On or near Major Road"
},
"longitude": "-0.064175"
},
"context": "",
"outcome_status": null,
"persistent_id": "",
"id": 53832841,
"location_subtype": "",
"month": "2016-12"
},
{
"category": "anti-social-behaviour",
"location_type": "Force",
"location": {
"latitude": "51.497877",
"street": {
"id": 953834,
"name": "On or near Major Road"
},
"longitude": "-0.064175"
},
"context": "",
"outcome_status": null,
"persistent_id": "",
"id": 53832849,
"location_subtype": "",
"month": "2016-12"
},
{
"category": "anti-social-behaviour",
"location_type": "Force",
"location": {
"latitude": "51.500440",
"street": {
"id": 953881,
"name": "On or near Chambers Street"
},
"longitude": "-0.066891"
},
"context": "",
"outcome_status": null,
"persistent_id": "",
"id": 53832881,
"location_subtype": "",
"month": "2016-12"
} ]
var categories = data.reduce(function(acc, crime) {
if (!acc[crime.category])
acc[crime.category] = 1;
else
acc[crime.category]++;
return acc;
}, {});
console.log(categories);
console.log(categories["Burglary"]);
Note that there's no such thing as a JSON object. Either you have JSON, which is a string representation/serialisation of your array/object, or you have an actual array or object.
Another approach, using Array#forEach.
var json = [{category:"Burglary",location_type:"Force",location:{latitude:"51.497877",street:{id:953834,name:"On or near Major Road"},longitude:"-0.064175"},context:"",outcome_status:null,persistent_id:"",id:53832838,location_subtype:"",month:"2016-12"},{category:"anti-social-behaviour",location_type:"Force",location:{latitude:"51.497877",street:{id:953834,name:"On or near Major Road"},longitude:"-0.064175"},context:"",outcome_status:null,persistent_id:"",id:53832841,location_subtype:"",month:"2016-12"},{category:"anti-social-behaviour",location_type:"Force",location:{latitude:"51.497877",street:{id:953834,name:"On or near Major Road"},longitude:"-0.064175"},context:"",outcome_status:null,persistent_id:"",id:53832849,location_subtype:"",month:"2016-12"},{category:"anti-social-behaviour",location_type:"Force",location:{latitude:"51.500440",street:{id:953881,name:"On or near Chambers Street"},longitude:"-0.066891"},context:"",outcome_status:null,persistent_id:"",id:53832881,location_subtype:"",month:"2016-12"}],
result = {};
json.forEach(function(v){
!result[v.category] ? result[v.category] = 1 : result[v.category] += 1;
});
console.log(result);
Use Array.prototype.reduce() function:
var data = [{category:"Burglary",location_type:"Force",location:{latitude:"51.497877",street:{id:953834,name:"On or near Major Road"},longitude:"-0.064175"},context:"",outcome_status:null,persistent_id:"",id:53832838,location_subtype:"",month:"2016-12"},{category:"anti-social-behaviour",location_type:"Force",location:{latitude:"51.497877",street:{id:953834,name:"On or near Major Road"},longitude:"-0.064175"},context:"",outcome_status:null,persistent_id:"",id:53832841,location_subtype:"",month:"2016-12"},{category:"anti-social-behaviour",location_type:"Force",location:{latitude:"51.497877",street:{id:953834,name:"On or near Major Road"},longitude:"-0.064175"},context:"",outcome_status:null,persistent_id:"",id:53832849,location_subtype:"",month:"2016-12"},{category:"anti-social-behaviour",location_type:"Force",location:{latitude:"51.500440",street:{id:953881,name:"On or near Chambers Street"},longitude:"-0.066891"},context:"",outcome_status:null,persistent_id:"",id:53832881,location_subtype:"",month:"2016-12"}],
counts = data.reduce(function (r, o) {
(r[o.category])? r[o.category]++ : r[o.category] = 1;
return r;
}, {});
console.log(counts);
You can do it with Array#reduce,
var arr = [{
"category": "Burglary",
}, {
"category": "anti-social-behaviour",
}, {
"category": "anti-social-behaviour",
}, {
"category": "anti-social-behaviour",
}];
var results = arr.reduce(function(result, itm){
return (result[itm.category] = (result[itm.category] || 0) + 1, result);
}, {});
console.log(results); //Object {Burglary: 1, anti-social-behaviour: 3}
DEMO
I'm using javascript to display information of a shop basket. I know how to pull the data and create elements from it, but I need to use one of the variables for an if statement, and am unsure how to.
If this is true: "isPunchOut": false, then I want to target that with jQuery, and do something like $(".button").remove();
How do I do this?
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "",
"phone": "",
"nbrOrders": 0,
"isPunchOut": false,
"name": "",
"salesPerson": "",
"customerNo": "",
"email": ""
},
"order": {
"shippingSum": 0.0,
"shippingFormatSum": "\u20AC0",
"orderno": "0",
"orderFormatSum": "\u20AC130",
"voucher": "",
"orderFormatVat": "\u20AC27,30",
"currencySymbol": "\u20AC",
"currency": "EUR",
"orderVat": 27.3,
"orderSum": 130.0,
"items": [{
"imageURI": "\/imgr\/8c82380c-65f5-43aa-83ad-fae1215b5b39\/70\/70",
"qtyAvail": 7,
"price": 130.0,
"qty": 1,
"artno": "D630-T7100-GE-REF",
"vat": 27.3,
"formatVat": "\u20AC27,30",
"id": "52307",
"label": "D630 C2D-T7100/2GB/80GB/DVD/14"/NO COA WLAN",
"category": "Computers - Notebooks",
"formatPrice": "\u20AC130",
"manufacturer": "Dell"
}]
}
}
You can take a look at below JS code for reference:
var isPunchOut = retailerData["user"]["isPunchOut"];
if(isPunchOut === false)
$(".button").remove();
I would say you should try some code first and put where you get stuck .We not here to write code for your problems.
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "",
"phone": "",
"nbrOrders": 0,
"isPunchOut": false,
"name": "",
"salesPerson": "",
"customerNo": "",
"email": ""
},
"order": {
"shippingSum": 0.0,
"shippingFormatSum": "\u20AC0",
"orderno": "0",
"orderFormatSum": "\u20AC130",
"voucher": "",
"orderFormatVat": "\u20AC27,30",
"currencySymbol": "\u20AC",
"currency": "EUR",
"orderVat": 27.3,
"orderSum": 130.0,
"items": [{
"imageURI": "\/imgr\/8c82380c-65f5-43aa-83ad-fae1215b5b39\/70\/70",
"qtyAvail": 7,
"price": 130.0,
"qty": 1,
"artno": "D630-T7100-GE-REF",
"vat": 27.3,
"formatVat": "\u20AC27,30",
"id": "52307",
"label": "D630 C2D-T7100/2GB/80GB/DVD/14"/NO COA WLAN",
"category": "Computers - Notebooks",
"formatPrice": "\u20AC130",
"manufacturer": "Dell"
}]
}
}
if(retailerData.user.isPunchOut){
//your jquery operation
}
Checkjsfiddle
What about?
if (!retailerData.user.isPunchOut) {
$(".button").remove();
}