How to append database values to JSON data - javascript

I have a JSON which lists the values from database. Below is the JSON data of 2 rows from the database.
[{"Name":"P1","Description":"pd1","Value":"v1","Attribute":"a1"},{"Name":"P1","Description":"pd1","Value":"v2","Attribute":"a2"}]
database values are the result of a left join query. Only 'Value' and 'Attribute' fields are different. Can I append that fields to JSON instead of multiple sets of record? I know there is 'push' to do this, but I am unaware where and how to use this in my code. below is the code for fetching values from db and serializing the values.
GetProfileDataService GetProfileDataService = new BokingEngine.MasterDataService.GetProfileDataService();
IEnumerable<ProfileData> ProfileDetails = GetProfileDataService.GetList(new ProfileSearchCriteria { Name = strProfileName });
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string strSerProfileDetails = javaScriptSerializer.Serialize(ProfileDetails);
context.Response.ContentType = "text/json";
context.Response.Write(strSerProfileDetails);
Below is my getJSON
$(document).ready(function () {
$.getJSON('ProfileHandler.ashx', { 'ProfileName': 'Profile 1' }, function (data) {
$.each(data, function (k, v) {
alert(v.Attribute+' : '+v.Value);
});
});
});
Please help me here.

There are several things you can do.
Store value and attribute as arrays:
[{"Name":"P1","Description":"pd1","Value":["v1", "v2"],"Attribute":["a1", "a2"]}]
Or store them as a 'symbol'-separated string:
[{"Name":"P1","Description":"pd1","Value":"v1;v2"],"Attribute":"a1;a2"]}]
In order to use the first case, you'll have to try and figure out how to format the ProfileDetails in order to have javaScriptSerializer.Serialize parse it correctly. You will likely have to convert your data first in order for this to work (i.e. convert value and attribute to arrays).
For the second case to work you could modify your GetProfileDataService.GetList method so that values and attributes are merged to symbol-separated strings (something like this: GROUP BY to combine/concat a column)

Related

How to fetch values from json array object without using object key name javascript?

Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc

javascript - JSON file use a value only if key exists

I'm retrieving an OSM Json from an overpass call, to obtain a list of features that I have to save on a database. Since the data are very different from one another (for example, some of them do have a a tag called "addr:city", and some of them not), I would like to check if a key exists, and only in that case save the corresponding value. I've found only this question but it's not my case, since I do not know a priori which keys one element will have and which not, and since I'm working with a great load of data, I really can't check the elements one by one and of course I can't write an IF for each case.
Is there a way to solve this? I was thinking something about "if key has null value, ignore it", while looping over the elements, but I don't know if something like that exists
EDIT:
This is my query:
https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696);way[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696););out%20center;
and this is the code I'm using to save the data on firebase:
results.elements.forEach(e=>{
var ref = firebase.database().ref('/point_of_interest/');
var key = firebase.database().ref().child('point_of_interest').push().key;
var updates = {};
var data = {
città: e.tags["addr:city"],
tipologia: e.tags["amenity"],
indirizzo: e.tags["addr:street"],
nome: e.tags["name"],
lat: e.lat,
lon: e.lon
}
updates['/point_of_interest/'+key] = data;
firebase.database().ref().update(updates);
})
"results" is the response in json format
You could use something like that:
var attrs = ["addr:city", "amenity", "addr:street", "name"];
var labels = ["città", "tipologia", "indirizzo", "nome"]
var data = { };
attrs.forEach((a, i) => {
if (e.tags[a]) { data[labels[i]] = e.tags[a]; }
});
You could even make this more dynamic, if you can query the attribute names and labels from somewhere.

Passing an array from Angular to php

I have a dropdown form where you can select one or more items. The selected items I want to send to a backend php script that will insert the selected values into a database.
This is my angular insert function:
insertRepair: function (id_telefon, id_culoare, arrayPiese) {
console.log(arrayPiese);
http.get('../php/insert_reparatii.php', {
params: {id_telefon: id_telefon, arrayPiese: arrayPiese,
id_culoare: id_culoare}
}).then(function () {
}
}
The call to this function is done like this:
serviceHttp.insertRepair($scope.phoneMP.selected.id, $scope.colorMP.selected.id, $scope.selectedPiesaMP.selected);
If I print into the console the arrayPiese array it will print for 2 selected items, something like this:
["Adezivi_Rama", "Polarizator"]
Now in the backend I retrieve the array list:
$arr = $_REQUEST['arrayPiese'];
If I print the $arr variable I get only one of two items printed.
Need to mention that I migrated from jquery to angular, and from jquery I was able to send the entire array like this:
var arrayPiese = [];
$('.select2-selection__choice').each(function () {
arrayPiese.push($(this).attr('id'));
});
The url looks like this arrayPiese=Adezivi_Rama&arrayPiese=Polarizator&id_culoare=1&id_telefon=18
Do I need to serialize the array before sending it to php? Or what would be the best approach in sending an array to backend??
You can pass array as json,
http.get('../php/insert_reparatii.php', {params: {id_telefon: id_telefon, arrayPiese:angular.toJson(arrayPiese),
id_culoare: id_culoare}
}).then(function () {
}
Then in your PHP script, convert json to PHP array,
$arrayPiese = json_decode($_GET['arrayPiese'], TRUE);
arrayPiese=Adezivi_Rama&arrayPiese=Polarizator will result in a single variable $_REQUEST['arrayPiese'] with the value Polarizator because the latter overwrites the first one.
If you want to pass an array, you have to append brackets to the query parameter name:
arrayPiese[]=Adezivi_Rama&arrayPiese[]=Polarizator
…which will result in a PHP variable $_REQUEST['arrayPiese'] with an array value like:
[
0 => 'Adezivi_Rama',
1 => 'Polarizator'
]

Overwriting Original Values In Collections

I am fetching data from database and storing it on $groups. It has different created_at for each entry.
I want to overwrite on created_at field in collection, just before returning it to the view, and have nice ->diffForHumans() version.
$groupsArray = $messages;
foreach($groupsArray as $key => $group) {
var_dump($groupsArray[$key]['created_at']); // works: 2015-10-17 21:55:46.000000'
var_dump($groupsArray[$key]['created_at']->diffForHumans()); // Error: A two digit month could not be found Data missing
$groupsArray[$key]['created_at'] = $groupsArray[$key]['created_at']->diffForHumans(); // Not Working
}
return $groupsArray->toJson();
If I change groupsArray = $messages->toArray();, the '// Error' bit of above chunk changes to Call to a member function diffForHumans() on string.
Eventually, I need to return it as json as it is ajax request. I want to overwrite on created_at, so I can use group[i]['created_at'] in javascript part in the view, after returning and get Carbon versions.
First, make sure 'created_at' is in your $dates array in your model.
Like described on http://laravel.com/docs/5.1/eloquent-mutators#date-mutators
Second, you can iterate and update over a collection by doing the following:
$messages->transform(function ($item, $key) {
$item->difference = $item->created_at->diffForHumans(); // 10 hrs ago
return $item;
});
$messages->toJson();
use &you can replace the original value !
foreach($groupsArray as &$key => &$group) {
var_dump($groupsArray[$key]['created_at']);
var_dump($groupsArray[$key]['created_at']->diffForHumans());
$groupsArray[$key]['created_at'] = $groupsArray[$key] ['created_at']->diffForHumans(); // Not Working
}

How to take data from Ext.Record?

I can take record from store: var record = store.getAt(i);
But if i want to take fileds which have a same name from record i get only first field value. For example if i have XML with:
Code:
<zem>
<parcel>
....
<parcel>
<really>
<price>555.555<price>
</really>
<really>
<price>666.666<price>
</really>
</zem>
And using record.get("price") i can get only 555.555 value.
Its possible to get values of all fields of <really>? Or array of values of all fields with name=<price>?
Take a walk on store:
var res = [];
store.each(function(record) { res.push(record.get('price')); })

Categories