Converting mysql query result into very specific json structure - javascript

I'm trying to get familiar with using php and javascript together in a joomla template, but I've moved it to a local box (no joomla, just testing the files on their own) to try and make more sense of it but I'm still stuck
I have a php function which is making a select on the database and returning the result, which is then passed to the default html file where I have my Javascript. So I'm getting the data passed to the page.
My issue is this: I have a mock JSON object in my Javascript that is structured exactly how I need/want it but I'm unsure of how I can convert my datebase result from SQL into this exact structure and replace the mock object.
Here is my query:
SELECT name, phone, address, city, state, zip, country, url, logo, lat, lng
from address_info
where published = 1
and when I dump the result on the page, this is the structure:
object(stdClass)#589 (11) {
["name"]=>
string(14) "TEST STORE"
["phone"]=>
string(12) "555-555-5555"
["address"]=>
string(18) "123 test ave"
["city"]=>
string(6) "Denver"
["state"]=>
string(8) "Colorado"
["zip"]=>
string(5) "80223"
["country"]=>
string(3) "USA"
["url"]=>
string(7) "http://test.com"
["logo"]=>
string(29) "logo.png"
["lat"]=>
string(12) "-104.9981929"
["lng"]=>
string(10) "39.7164275"
}
Any help on how to convert this result into the exact JSON structure is greatly appreciated
<script type="text/javascript">
const stores = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-77.034084142948, 38.909671288923]
},
'properties': {
'storeImage' : 'https://via.placeholder.com/150',
'storeName' : 'Test Store',
'phoneFormatted': '(202) 234-7777',
'address': '1471 P St NW',
'city': 'Washington DC',
'country': 'United States',
'postalCode': '20005',
'state': 'D.C.'
}
},
]
};
</script>

You need to manually assign all values to their corresponding place. So in your specific use case, this would look like this:
// I've set your result from MySQL to be stored in $data
// Populate a new array
$return = [
'type' => 'FeatureCollection',
'feature' => [
[
'type' => 'Feature',
'geometry' => [
'type' => 'Point',
'coordinates' => [
$data->lat,
$data->lng
]
],
'properties' => [
'storeImage' => $data->logo, // you need to convert this into an actual URL
'storeName' => $data->name,
'phoneFormatted' => $data->phone, // this needs formatting aswell
'address' => $data->address,
'city' => $data->city,
'country' => $data->country,
'postalCode' => $data->zip,
'state' => $data->state
]
]
]
];
// output the PHP array as JSON
echo json_encode($return);

Related

converting enum object to array returns extra object in javascript

I would like to know how to convert enum object to array of objects in javascript
It works, but am getting the output with four object arrays instead of two object arrays
const result = Object.entries(countries).map(([value, key]) =>
({ country: value.toLowerCase(), id: key })
);
enum countries {
SINGAPORE = 123,
DENMARK = 246
}
Actual Output:
[
{country: '123', id: 'singapore'}
{country: '246', id: 'denmark'}
{country: 'singapore', id: 123}
{country: 'denmark', id: 246}
]
Expected Output:
[
{country: "singapore", id: 123},
{country: "denmark", id: 246}
]
It's important to understand the JavaScript that typescript generates when you use enum - yours will look like this:
{
"123":"SINGAPORE",
"246":"DENMARK",
"SINGAPORE":123,
"DENMARK":246
}
Which should make it clear why you get 4 items when you enumerate it using Object.entries (or Object.keys etc).
You can filter out the numeric values if you wish
var countries = {
"123":"SINGAPORE",
"246":"DENMARK",
"SINGAPORE":123,
"DENMARK":246
}
const result = Object.entries(countries)
.filter(([key,_]) => !isNaN(key))
.map(([key, value]) => ({ country: value.toLowerCase(), id: key }));
console.log(result);

JS Data object is not iterable in console

Currently I'm trying to call a function with a data response from an ajax call, and I'm getting that my constant stores is not iterable. My AJAX call looks like this
jQuery.ajax({
type: 'GET',
url: "<?php echo JURI::base() . "index.php?option=com_ajax&module=hunter_maps_dev&method=getStoresByZip&zip="?>" +zip+ "&format=json",
datatype : "application/json",
success:function(data){
console.log('success');
const stores = data;
console.log(stores);
buildLocationList(stores);
},
...
function buildLocationList({ features }) {
for (const { properties } of features) {
}
}
and I'm logging it to the console.
I'm getting this for the data in the console: data: "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.9981929\",\"39.7164275\"]},\"properties\":{\"store
and this is the mock I was previously using:
const stores = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-77.034084142948, 38.909671288923]
},
'properties': {
'storeImage' : 'https://via.placeholder.com/150',
'storeName' : 'Test Store',
'phoneFormatted': '(202) 234-7777',
'phone': '2022347336',
'address': '1471 P St NW',
'city': 'Washington DC',
'country': 'United States',
'crossStreet': 'at 15th St NW',
'postalCode': '20005',
'state': 'D.C.'
}
},
]
};
What is missing for me to get this to match the mock format so that it's iterable?
UPDATE: Full response currently
{"success":true,"message":null,"messages":null,"data":"{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.9981929\",\"39.7164275\"]},\"properties\":{\"storeImage\":\"1542820219karmalogo2-Copy.png\",\"storeName\":\"Karmaceuticals\",\"phoneFormatted\":\"303-765-2762\",\"address\":\"4 S Santa Fe Drive\",\"city\":\"Denver\",\"country\":\"USA\",\"postalCode\":\"80223\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.8526653\",\"39.7861717\"]},\"properties\":{\"storeImage\":\"1438052652medicineman_logo_web.jpg\",\"storeName\":\"Medicine Man - Denver\",\"phoneFormatted\":\"303-373-0752\",\"address\":\"4750 Nome St.\",\"city\":\"Denver\",\"country\":\"Denver\",\"postalCode\":\"80239\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-105.0135439\",\"39.7206576\"]},\"properties\":{\"storeImage\":\"1455044497CannaBoticaOrange.png\",\"storeName\":\"CannaBotica \",\"phoneFormatted\":\"303-777-1550\",\"address\":\"219 Vallejo st.\",\"city\":\"Denver\",\"country\":\"United States\",\"postalCode\":\"80223\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.8664385\",\"39.6817321\"]},\"properties\":{\"storeImage\":\"1458987858medicine-man-aurora.jpg\",\"storeName\":\"Medicine Man - Aurora\",\"phoneFormatted\":\"303-923-3825\",\"address\":\"1901 S Havana Street\",\"city\":\"Aurora\",\"country\":\"\",\"postalCode\":\"80014\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-116.905029\",\"33.0433045\"]},\"properties\":{\"storeImage\":\"1479714765showgrow-logo.jpg\",\"storeName\":\"Showgrow - Ramona\",\"phoneFormatted\":\"760-687-9700\",\"address\":\"736 Montecito Way\",\"city\":\"Ramona\",\"country\":\"United States\",\"postalCode\":\"92065\",\"state\":\"California\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-117.8467455\",\"33.7201192\"]},\"properties\":{\"storeImage\":\"1479715612showgrow-logo.jpg\",\"storeName\":\"Showgrow -Santa Ana\",\"phoneFormatted\":\"949-565-4769\",\"address\":\"1625 E St Gertrude Pl\",\"city\":\"Santa Ana\",\"country\":\"United States\",\"postalCode\":\"92705\",\"state\":\"California\"}}]}"}
You need to parse the JSON string to convert it to an object:
buildLocationList(JSON.parse(stores));

Parsing array of objects to format data

I have an array of cities with this structure (given from the CMS):
const cities = [
{
city: 'Genova',
coordinates: '{\'type\':\'Point\',\'coordinates\':[8.9473343,44.4023918]}',
countryIsoCode: 'it',
description: 'test',
isInitialCity: true,
}, {
city: 'Barcelona',
coordinates: '{\'type\':\'Point\',\'coordinates\':[2.0951271,41.3397004]}',
countryIsoCode: 'es',
description: 'description',
isInitialCity: false,
}, {
city: 'Sydney',
coordinates: '{type\':\'Point\',\'coordinates\':[151.2158203,-33.8704156]}',
countryIsoCode: 'au',
description: 'Sydney description',
isInitialCity: false,
}];
I want to parse the coordinates position to get a more scalable object and get its properties nesting.
This is what I've tried:
cities.map(city=>JSON.parse(city.coordinates))
But when I print it seems to have no effect. However, if I manually print a position like console.log(JSON.parse(cities[0].coordinates)) it shows a formatted result like is shown in the following screenshot:
How can I make it automatically via loop?
This is what I've tried:
cities.map(city=>JSON.parse(city.coordinates))
map() created you a brand new, separate array with the coordinates only, which you have thrown away afterwards.
However, if I manually print a position like console.log(JSON.parse(cities[0].coordinates)) [...] How can I make it automatically via loop?
Well, put it in a loop:
for(let city of cities)
city.coordinates = JSON.parse(city.coordinates);
However your example data is syntactically incorrect, there are ,}-s at the end of the objects (after the true/false), and the supposed JSON data is not JSON, like
{type':'Point','coordinates':[151.2158203,-33.8704156]}
^it has no pair, and it should be double quote anyway, all of them
{"type":"Point","coordinates":[151.2158203,-33.8704156]} <-- this is JSON
What I think might be happening is that you're doing the map right but not returning the result.
For example mynumbers.map(num => num++) won't actually effect mynumbers at all. You have to assign the result of the map to another variable...
const parsedCities = cities.map(city=>JSON.parse(city.coordinates))
Now your new parsedCities variable will look like you want it to and the original cities array will remain unchanged.
const cities = [
{
city: 'Genova',
coordinates: '{\'type\':\'Point\',\'coordinates\':[8.9473343,44.4023918]}',
countryIsoCode: 'it',
description: 'test',
isInitialCity: true,
}, {
city: 'Barcelona',
coordinates: '{\'type\':\'Point\',\'coordinates\':[2.0951271,41.3397004]}',
countryIsoCode: 'es',
description: 'description',
isInitialCity: false,
}, {
city: 'Sydney',
coordinates: '{type\':\'Point\',\'coordinates\':[151.2158203,-33.8704156]}',
countryIsoCode: 'au',
description: 'Sydney description',
isInitialCity: false,
}];
//for(let city of cities)
// city.coordinates = JSON.parse(city.coordinates);
var x=cities.map(city=>JSON.parse(JSON.stringify(city.coordinates)))
console.log("result :"+(JSON.stringify(x)))
// result :["{'type':'Point','coordinates':[8.9473343,44.4023918]}","{'type':'Point','coordinates':[2.0951271,41.3397004]}","{type':'Point','coordinates':[151.2158203,-33.8704156]}"]

How to add names to an array of unnamed JSON objects?

So I'm currently using csvtojson in order to convert a csv file to, well, json, and my code is returning an array of unnamed objects. However, I want these objects to be named. More specifically, I want to use the values from the first column in order to name the objects.
My CSV file looks like this:
First Name, Restaurant, Food Name, Comment, Price
Andrew, Clucky's Chicken, Chickenator, This sandwich is awesome, $9.99
Michelle, Bytes, Big Burger, Burger was too well done, $12.99
Cam, Candyland, Yummy Gummies, Good price for bulk candy, $1.75
I'm using this code and running it in node:
// require the csvtojson converter class
var Converter = require("csvtojson").Converter;
//create a new converter object
var converter = new Converter({});
//call the fromFile function which takes in the path to the csv file, as well as a callback function
converter.fromFile("./restaurants.csv", function(err,result){
// if an error has occurred, then handle it
if(err){
console.log("An error has occurred");
console.log(err);
}
// create a variable called json and store the result of the conversion
var json = result;
// log our json to verify it has worked
console.log(json);
});
Which returns:
[ { 'First Name': 'Andrew',
'Restaurant': 'Clucky's Chicken',
'Food Name': 'Chickenator',
'Comment': 'This sandwich is awesome',
'Price': '$9.99' },
{ 'First Name': 'Michelle',
'Restaurant': 'Bytes',
'Food Name': 'Big Burger',
'Comment': 'Burger was too well done',
'Price': '$12.99' },
{ 'First Name': 'Cam',
'Restaurant': 'Candyland',
'Food Name': 'Yummy Gummies',
'Comment': 'Good price for bulk candy',
'Price': '$1.75' } ]
But I would like it to return something more along the lines of:
[ Andrew : { 'Restaurant': 'Clucky's Chicken',
'Food Name': 'Chickenator',
'Comment': 'This sandwich is awesome',
'Price': '$9.99' },
Michelle : { 'Restaurant': 'Bytes',
'Food Name': 'Big Burger',
'Comment': 'Burger was too well done',
'Price': '$12.99' },
Cam : { 'Restaurant': 'Candyland',
'Food Name': 'Yummy Gummies',
'Comment': 'Good price for bulk candy',
'Price': '$1.75' } ]
Anybody have any suggestions on how I can do this?
Make a custom function (since you want to convert array into a map).
function arrayToMap(array) {
var map = {};
array.map(
(element) => {
var firstName = element['First Name'];
delete element['First Name'];
map[firstName] = element;
}
);
return map;
}
Create a new array itemArray, then loop for all item in array and push it to itemArray
var itemArray = []
a.map(item => {
firstName = item["First Name"];
delete item["First Name"];
itemArray[firstName] = item;
})
console.log(itemArray); // <<<< you get the result here

How to rearrange CSV / JSON keys columns? (Javascript)

I am converting a JSON object array to CSV using Papa Parse JavaScript Library. Is there a way to have the CSV columns arranged in a certain way.
For e.g; I get the column as:
OrderStatus, canOp, OpDesc, ID, OrderNumber, FinishTime, UOM, StartTime
but would like to be arranged as:
ID, OrderNumber, OrderStatus, StartTime, FinishTime, canOp, OpDesc, UOM
The reason why I get the CSV as unarranged is because the JSON data looks like this:
json = [
{
OrderStatus: "Good",
canOp:"True",
OpDesc:"Good to go",
ID:"100",
OrderNumber:"1000101",
FinishTime:"20:50",
UOM:"K",
StartTime:"18:10"
},
...
]
Thanks
Papa Parse allows to specify order of fields in the unparse() function:
var csv = Papa.unparse({
fields: ["ID", "OrderNumber", "OrderStatus", "StartTime", "FinishTime", "canOp", "OpDesc", "UOM"],
data: [{
OrderStatus: "Good",
canOp: "True",
OpDesc: "Good to go",
ID: "100",
OrderNumber: "1000101",
FinishTime: "20:50",
UOM: "K",
StartTime: "18:10"
},
// ...
]
});
console.log(csv);
<script src="https://unpkg.com/papaparse#4.6.3/papaparse.min.js"></script>
<h3>See your dev console for the results</h3>
You don't need any framework to convert from json to csv.
// fields in the order you want them
const fields = ['ID', 'OrderNumber', 'OrderStatus', 'StartTime', 'FinishTime', 'canOp', 'OpDesc', 'UOM'];
const mapper = (key, value) => value === null ? '' : value // how to handle null values
const csv = [
fields.join(','), // header row
...json.map((row) => fields.map((fieldName) => JSON.stringify(row[fieldName], mapper))).join(',')
]
console.log(csv.join('\r\n'))
Outputs:
ID,OrderNumber,OrderStatus,StartTime,FinishTime,canOp,OpDesc,UOM
"100","1000101","Good","18:10","20:50","True","Good to go","K"
"100","1000101","Good","18:10","20:50","True","Good to go","K"

Categories

Resources