Sort internal array timestamps - javascript

I have an array with multiple elements that looks like this:
{
"name": "DR",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
]
],
"type": "areaspline"
},
{
"name": "SIT",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
],
[
"1506384000000",
3
],
[
"1534204800000",
1
],
[
"1531094400000",
1
],
[
"1528502400000",
1
]
],
"type": "areaspline"
},
This is the exact format I use to send data into high charts, however, the problem is that the chart breaks if the timestamps inside each environment (DR, SIT) are not in order.
How can I sort the 'data' inside each environment by timestamp?
This JSON is generated in PHP and sent through to JavaScript. So I would like to know how to sort the data inside either PHP or JavaScript.
Thanks.

This is actually rather trivial, once you know about the usort function. It allows you to define your own sorting function, so you can sort based on any factor of whatever the 2 objects it is passed.
Note that from your example json I had to add a set of square brackets around the whole thing to get PHP to parse it with json_decode .
<?php
// note I had to add square brackets to your
// demo json ....
$json='[{
"name": "DR",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
]
],
"type": "areaspline"
},
{
"name": "SIT",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
],
[
"1506384000000",
3
],
[
"1534204800000",
1
],
[
"1531094400000",
1
],
[
"1528502400000",
1
]
],
"type": "areaspline"
}]';
$json_obj_arr=json_decode($json,true);
print_r($json_obj_arr);
print("\n\n");
// a function to handle the sorting itself
// usort will pass it an array(timestamp,datavalue) for both
// $a and $b so we compare the [0] element of each
function cmp($a, $b)
{
if ($a[0] == $b[0]) {
return 0;
}
return ($a[0] < $b[0]) ? -1 : 1;
}
// loop through the array, first is indexed
for($i=0;$i<count($json_obj_arr);$i++){
// then each one of those contains an
// associtive array with an element named ['data'] -
// this is an indexed array that you want sorted
// on the [0] element
usort($json_obj_arr[$i]['data'],"cmp");
}
print_r($json_obj_arr);
print("\n\n");
?>

Related

How to fill an object into specific properties of another object?

I have an object a and i want to map the values of a into another object andoridConfig such that splashLdpi will have value of what 120x120 has i mean the url,splashMdpi will have value of what 160x160 has,splashHdpi will have a value of what 240x240 has and so on.
a = {
"120x120": [
"https://storage.googleapis.com/zopping-staging-uploads/120x120/20211221/wallpaperflarecomwallpaper-20211221-104553.jpg"
],
"160x160": [
"https://storage.googleapis.com/zopping-staging-uploads/160x160/20211221/wallpaperflarecomwallpaper-20211221-104553.jpg"
],
"240x240": [
"https://storage.googleapis.com/zopping-staging-uploads/240x240/20211221/wallpaperflarecomwallpaper-20211221-104553.jpg"
],
"320x320": [
"https://storage.googleapis.com/zopping-staging-uploads/320x320/20211221/wallpaperflarecomwallpaper-20211221-104553.jpg"
],
"480x480": [
"https://storage.googleapis.com/zopping-staging-uploads/480x480/20211221/wallpaperflarecomwallpaper-20211221-104553.jpg"
],
"640x640": [
"https://storage.googleapis.com/zopping-staging-uploads/640x640/20211221/wallpaperflarecomwallpaper-20211221-104553.jpg"
]
}
"androidAppConfig": {
"playStoreServiceAccount": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchercircle-20211020-112456.png",
"fbServiceAccount": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchercircle-20211020-112456.png",
"icon512x512": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchercircle-20211020-112456.png",
"banner1024x500": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchercircle-20211020-112456.png",
"iconMdpiCircle": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchercircle-20211020-112456.png",
"iconMdpiSquare": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchersq-20211020-112533.png",
"iconHdpiCircle": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchercircle-20211020-112842.png",
"iconHdpiSquare": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchersq-20211020-112946.png",
"iconXhdpiCircle": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchercircle-20211020-112201.png",
"iconXhdpiSquare": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchersq-20211020-112251.png",
"iconXxhdpiCircle": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchercircle-20211020-111829.png",
"iconXxhdpiSquare": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchersq-20211020-111956.png",
"iconXxxhdpiCircle": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchercircle-20211020-111431.png",
"iconXxxhdpiSquare": "https://storage.googleapis.com/zopping-uploads/originals/20211020/iclaunchersq-20211020-111631.png",
"splashLdpi": "https://storage.googleapis.com/zopping-uploads/originals/20211020/splash-20211020-112750.webp",
"splashMdpi": "https://storage.googleapis.com/zopping-uploads/originals/20211020/splash-20211020-112645.webp",
"splashHdpi": "https://storage.googleapis.com/zopping-uploads/originals/20211020/splash-20211020-113200.webp",
"splashXhdpi": "https://storage.googleapis.com/zopping-uploads/originals/20211020/splash-20211020-112353.webp",
"splashXxhdpi": "https://storage.googleapis.com/zopping-uploads/originals/20211020/splash-20211020-112053.webp",
"splashXxxhdpi": "https://storage.googleapis.com/zopping-uploads/originals/20211020/splash-20211020-111724.webp"
},
How do i acheive it?
I am thinking of extracting all the urls from object a into an array first and then somehow use that to fill androidAppConfig.

Fetch data from a nested array

I would like to know if there is a way to get the length from a nested array.
My data is a JSON file like this:
{
"data" :[
"item1" :'',
"item2" :[{
"id" :1,
"text":'text'
},{
"id" :2,
"text" : 'text
}]
]
}
I'm using angular 6 and ngx-restangular.
Is possible to get the item 2 length?
The main problem is the question does not provide a valid json. A valid json for the same would be like as under :
{
"data": {
"item1": "",
"item2": [{
"id": 1,
"text": "text"
},
{
"id": 2,
"text": "text"
}
]
}
}
Now you can fetch the second element size simply by
data["item2"].length
or
data.item2.length
To extend the Answer from #AurA
If you had to work with a valid array:
[
[ "item0.0", "item0.1" ],
[ "item1.0", "item1.1" ]
]
you could access the length of the nested arrays like this:
let a = [
["item0.0", "item0.1"],
["item1.0", "item1.1"]
];
let lengthA0 = a[0].length;
let lengthA1 = a[1].length;
console.log("length of a0: ", lengthA0);
console.log("length of a1: ", lengthA1);

Javascript/json keep in database and special chars

I have layout builder in React to keep data structure and text I use ImmutableJS objects.
Such structure with attributes as text or css styles is saved into database as JSON.
To make it JSON I using json-immutable library: serialize, deserialize functions.
After save in database I provide configuration for react components as javascript variables. For example my backend generate js file with variables or small part is printing directly in html code using script tag.
Data are JSON or decoded javascript.
The biggest problem I have with save special chars.
For example if someone set ' single quote in some attribute it is saved directly.
But when I print it in html code as
var myConfig = '{anyjson}';
when inside JSON is single quote parser throw error. The same with double quotes, & (ampersant) or any chars used in html code like <,/>
Single quote I replace to \' when I print it in html code.
But I think does exists any way to save keep all data in JSON and still they will easy to decode by deserialize function to parse JSON to ImmutableJS objects.
Code example
https://jsfiddle.net/jaroapp/2yzud6ua/2/
var structure = {
"__iterable":"Map",
"data":[
[
"entityMap",
{
"__iterable":"Map",
"data":[
[
"html_el_qb7tyhi",
{
"__iterable":"Map",
"data":[
[
"imported",
false
],
[
"path",
"html_el_qb7tyhi"
],
[
"componentData",
{
"__iterable":"Map",
"data":[
]
}
],
[
"draftjsObject",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"draftjs",
true
],
[
"data",
{
"__iterable":"OrderedMap",
"data":[
[
"text",
"B&B is the best company. It's my hope for new markets."
]
]
}
],
[
"chunk",
null
],
[
"style",
{
"__iterable":"OrderedMap",
"data":[
[
"background-image",
"url(\"/path/to/image.jpg\")"
]
]
}
],
[
"attr",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"runEditor",
false
],
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"type",
"div"
],
[
"key",
"html_el_qb7tyhi"
]
]
}
],
[
"html_el_2dgupn7",
{
"__iterable":"Map",
"data":[
[
"imported",
false
],
[
"path",
"html_el_2dgupn7"
],
[
"componentData",
{
"__iterable":"Map",
"data":[
]
}
],
[
"draftjsObject",
{
"entityMap":{
},
"blocks":[
{
"key":"3ia22",
"text":"Text saved with html inside",
"type":"unstyled",
"depth":0,
"inlineStyleRanges":[
],
"entityRanges":[
],
"data":{
}
}
]
}
],
[
"draftjs",
true
],
[
"data",
{
"__iterable":"OrderedMap",
"data":[
[
"text",
null
],
[
"html",
"<p class=\"md-block-unstyled\">Text saved with html inside</p>"
]
]
}
],
[
"chunk",
null
],
[
"style",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"attr",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"runEditor",
false
],
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"type",
"div"
],
[
"key",
"html_el_2dgupn7"
]
]
}
]
]
}
],
[
"containersMap",
{
"__iterable":"Map",
"data":[
]
}
],
[
"componentsMap",
{
"__iterable":"Map",
"data":[
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
]
]
}
]
]
};
Such structure I set as parameter into ReactJS component.
If I set it as JSON and wrap in quotes then the browser throws an error. If I set it as JavaScript object into the React component I can't make ImmutableJS from this one, because this structure is read by this
https://www.npmjs.com/package/json-immutable library (I use the same to make JSON from Immutable JS to save it in database);
Thanks in advance for any hints.
I solved this problem. Short description, maybe will helpful for someone.
I get file with deserialize function form json-immutable package. And I modified function deserialize to
export function deserialize(json){
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if(typeof json==='string'){
return JSON.parse(json, function(key, value, options){
return revive(key, value, options);
});
}else{
return JSON.parse(JSON.stringify(json), function(key, value, options){
return revive(key, value, options);
});
}
}
Function in package use JSON.parse for param. Maybe it's not the most elegant solution but I don't have time to find way to don't "re-json" object. Standard Object.keys and map return origin object.

How to parse JSON data from nested array in PHP

I am struggling to retrieve some values from a JSON file formatted like this:
{
"#context": [
"https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld",
{
"wx": "https://api.weather.gov/ontology#",
"#vocab": "https://api.weather.gov/ontology#"
}
],
"type": "FeatureCollection",
"features": [
{
"id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-95.45,
32.36
],
[
-96.07,
32.36
],
[
-96.08,
32.76
],
[
-95.92,
32.82
],
[
-95.85,
32.77
],
[
-95.77,
32.77
],
[
-95.76,
32.75
],
[
-95.71,
32.75
],
[
-95.66,
32.71
],
[
-95.64,
32.72
],
[
-95.59,
32.68
],
[
-95.6,
32.48
],
[
-95.47,
32.37
],
[
-95.45,
32.36
]
]
]
},
"properties": {
"#id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485131-2320093",
"#type": "wx:Alert",
"id": "NWS-IDP-PROD-2485131-2320093",
"areaDesc": "Van Zandt",
"geocode": {
"UGC": [
"TXC467"
],
"SAME": [
"048467"
]
},
"references": [],
"sent": "2017-08-13T00:03:41+00:00",
"effective": "2017-08-13T00:03:41+00:00",
"onset": "2017-08-13T00:03:00+00:00",
"expires": "2017-08-13T01:00:00+00:00",
"ends": "2017-08-13T01:00:00+00:00",
"status": "Actual",
"messageType": "Alert",
"category": "Met",
"severity": "Severe",
"certainty": "Observed",
"urgency": "Immediate",
"event": "Severe Thunderstorm Warning",
"sender": "NWS Fort Worth TX",
"headline": "Severe Thunderstorm Warning issued August 12 at 7:03PM CDT expiring August 12 at 8:00PM CDT by NWS Fort Worth TX",
"description": "The National Weather Service in Fort Worth has issued a\n\n* Severe Thunderstorm Warning for...\nVan Zandt County in north central Texas...\n\n* Until 800 PM CDT.\n\n* At 703 PM CDT, a severe thunderstorm was located near Wills Point,\nmoving east at 25 mph.\n\nHAZARD...65 mph wind gusts and quarter size hail.\n\nSOURCE...Radar indicated.\n\nIMPACT...Hail damage to vehicles is expected. Expect wind damage\nto roofs, siding, and trees.\n\n* This severe thunderstorm will be near,\nCanton around 710 PM CDT.\nEdgewood around 715 PM CDT.\nFruitvale around 725 PM CDT.\nGrand Saline around 735 PM CDT.\nVan around 750 PM CDT.\n\nThis includes Interstate 20 between mile markers 513 and 542.",
"instruction": "For your protection get inside a sturdy structure and stay away from\nwindows.\n\nContinuous cloud to ground lightning is occurring with this storm.\nMove indoors immediately. Lightning can kill.\n\nHeavy rainfall is occurring with this storm, and may lead to flash\nflooding. Do not drive your vehicle through flooded roadways.",
"response": "Shelter",
"parameters": {
"eventMotionDescription": [
"2017-08-13T00:03:00.000-05:00...storm...277DEG...23KT...32.62,-95.97"
],
"hailSize": [
"1.00"
],
"windGust": [
65
],
"tornadoDetection": [
"POSSIBLE"
],
"VTEC": [
"/O.NEW.KFWD.SV.W.0313.170813T0003Z-170813T0100Z/"
],
"EAS-ORG": [
"WXR"
],
"PIL": [
"FWDSVRFWD"
],
"BLOCKCHANNEL": [
"CMAS",
"EAS",
"NWEM"
],
"eventEndingTime": [
"2017-08-13T01:00:00Z"
]
}
}
},
I am trying to get the values from the keys under the "properties" key. What I am struggling with is does the array start with "properties" nested under #context or under "features"? I am not familiar with JSON data that uses # keys.
There are more values I need. But for starters, I am just using the event key nested under "features" -> "properties" where most of the keys for the values I need. I am not getting output from that.
<?php
$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$result = json_decode($data, true); // decode the JSON feed
foreach($results as $result) {
dump($result); //this will dump the array
foreach($results['features'] as $data) {
dump($data['event']);
}
}
?>
-Thanks
EDIT: Added suggestion to code for json_decode
As others have stated, you need to pass true as a second param to json_decode if you want to the result to be an associative array.
The hierarchy is features/properties/event so you can look through the features and pull what you want out of the properties of each feature.
<?php
$url = 'http://stream.dfwstormforce.com/json/nat_alerts.json'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$results = json_decode($data, true); // decode the JSON feed
foreach($results['features'] as $currFeature)
{
$currEvent = $currFeature['properties']['event'];
echo $currEvent."\n";
}
Use json_decode($data, true). The true tells json_decode to return nested associative arrays instead of a object.
As BarNakedCoder said:
json_decode($data, true)
but you also need to replace
dump($data['event']
with:
dump($data[0]['event'])

Sending data to the frontend from Nodejs

I am formatting some data to be more readable.
I am sending this data to the frontend, look
code
res.status(200).json({dealersData});
dealersData is a json containing
{
"Dealers":{
"Detail":[
{
"Table":[
{
"DealerId":[
"1"
],
"DealerName":[
"Carmen"
],
"NickName":[
"Carmen"
],
"Picture":[
"00001.jpg"
],
"Active":[
"1"
],
"LegalId":[
"111111111"
],
"TypeId":[
"1"
]
}
]
}
]
}
}
so what I need to do with Lodash is send the data to the frontend without the '"Dealers":{...}and without the '"Detail":[...]' part, I need to send it starting the JSON from"Table"`
lets say like this
{
"Table":[
{
"DealerId":[
"1"
],
"DealerName":[
"Carmen"
],
"NickName":[
"Carmen"
],
"Picture":[
"00001.jpg"
],
"Active":[
"1"
],
"LegalId":[
"111111111"
],
"TypeId":[
"1"
]
}
I already tried but I am getting something like
dealersData {[[null]]}
so, what are your suggestions ?
res.status(200).json(dealersData.Dealers.Detail[0]);
Access Dealers key, then first object in Detail array
Just change your response to:
res.status(200).json(dealersData.Dealers.Detail[0]);
Perhaps check data validity:
if(dealersData && dealersData.Dealers && dealersData.Dealers.Detail) {
res.status(200).json(dealersData.Dealers.Detail[0]);
} else {
res.status(404).json({'success':false});
}

Categories

Resources