javascript json get data names out for object - javascript

Still newbie #this, hope not a silly question.
I get from a java backend a json.
For this question I assigned a with that json string.
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
let b=a.data;
let s="";
for (i in b) {s += b[i]};
$('#msg').html(s);
As output I get object Object (small capital, big capital)
In the end I need to run over "data' and print or store that keynames : blablaMOUTI blablaDAN , blablaDAA blablaALHAZO ... on screen or in a simple array list.
The values after the keynames or a empty string, that's fine, I need only the keynames.
Found some semi simular questions, but I don't get it to work. The answers I found all trust I know already the keynames.

You can do it like this:
let a={"status":"ok","data":[{"blablaMOUTI blablaDAN":"","blablaDAA blablaALHAZO":"","blablaMAR blablaBDAN":"","blablaHIM blablaDAN":""}]};
var keys = [];
for(i = 0; i< a.data.length; i++){
for(var k in a.data[i]) {
keys.push(k);
}
}
console.log(keys)
For testing purpose this will populate an array with keys that you wanted, but you can manipulate the result as you wish

Object.getOwnPropertyNames(a.data[0]);
Output:  ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

Try this:
Object.getOwnPropertyNames(a.data[0]);
Output:  ["blablaMOUTI blablaDAN", "blablaDAA blablaALHAZO", "blablaMAR blablaBDAN", "blablaHIM blablaDAN"]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames

Related

Angularjs splitting into array

I want my data to be stored in an array but mine is stored in a single array, how to split it into like array. This is how it looks like, im spliting it via "|" but i want to store them into array~
JS:
{
$scope.polygonPoints.push($scope.apiResult[i].LatLng)
$scope.polyLineCord.push($scope.polygonPoints[i].split("|"))
console.log($scope.polygonPoints)
for (var k= 0; k < $scope.polyLineCord.length; k++) {
console.log($scope.polyLineCord)
$scope.Lat.push($scope.polyLineCord[k].split(',')[0]);
$scope.Lng.push($scope.polyLineCord[k].split(',')[1]);
L.marker([$scope.Lat[k], $scope.Lng[k]], {icon: greenIcon}).bindPopup($scope.apiResult[k].DESCRIPTION).addTo(cities);
}
}
Sry if the phrasing sounds werid, basically what I want it like "1.309..., 103.844" into array[0] and and "1.30916..., 103.845..." into array1 and so on
You can use es6 features using map for example :
$scope.polygonPoints = ["1.3|1.2|1.5", "1.5|2.2"];
$scope.polygonPoints.map(res => res.split('|'));
result:
["1.3", "1.2", "1.5"] // array one
["1.5", "2.2"] // array two

How to load language keys from separate js file?

This is my app.js
app.js
$translateProvider.registerAvailableLanguageKeys(['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'], {
'en-*':'en_US',
'es-*':'es_ES',
'pt-*':'pt_PT',
'fr-*':'fr_FR',
'de-*':'de_DE',
'ja-*':'ja_JP',
'it-*':'it_IT',
'*':'en_US'
})
}
]
keys (['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
and
'en-*':'en_US',
'es-*':'es_ES',
'pt-*':'pt_PT',
'fr-*':'fr_FR',
'de-*':'de_DE',
'ja-*':'ja_JP',
'it-*':'it_IT',
'*':'en_US'
How can i get these keys from a global object from outside javascript file since im repeating these keys in other places.
My javascript file has these two arrays.
keys.js
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
How can i use this javascript file to get iterate key value pair in app.js and other places instead of repeating it everywhere.
If your goal is to create an object with key-value pairs from the two arrays you could do the following:
var obj = {};
for (var i = 0; i < commonKeys.length; i++) {
obj[commonKeys[i]] = keys[i];
}
console.log(obj);
Or, if you are ok with using a third-party library, you could include underscore.js and use the _.object function like this:
var obj = _.object(commonKeys, keys);
console.log(obj);
In both cases the output of the js console would be
Object {en-*: "en_US", es-*: "es_ES", pt-*: "pt_PT", fr-*: "fr_FR", de-*: "de_DE"…}

passing python list to javascript

I am trying to pass a python list to a javascript function, but it doesn't work... I think the Javascript function will see it as one long string. This is what I do:
#webiopi.macro
def calcSunriseSunsetOneYear():
o=ephem.Observer()
o.lat='51.21828'
o.long='3.94958'
s=ephem.Sun()
d=datetime.date.today()
t=timedelta(days=1)
d=d+t
o.date=d
riseTime=[]
setTime=[]
s.compute()
for x in range (0,365):
o.date=o.date+1
riseTime.append(str(ephem.localtime(o.next_rising(s))))
setTime.append(str(ephem.localtime(o.next_setting(s))))
return(json.dumps(riseTime))
This is the python data:
["2015-03-22 06:43:02.000006", "2015-03-23 06:40:46", "2015-03-24 06:38:31.000001", "2015-03-25 06:36:15.000002", "2015-03-26 06:33:59.000003", "2015-03-27 06:31:44.000004", "2015-03-28 06:29:28.000005", "2015-03-29 07:27:13.000006", "2015-03-30 07:24:57", "2015-03-31 07:22:42.000001", "2015-04-01 07:20:27.000002", "2015-04-02 07:18:13.000003", "2015-04-03 07:15:58.000004", "2015-04-04 07:13:44.000005", "2015-04-05 07:11:31.000006", "2015-04-06 07:09:17", "2015-04-07 07:07:04.000001", "2015-04-08 07:04:52.000002", "2015-04-09 07:02:40.000003", "2015-04-10 07:00:28.000004"]
In Javascript I do this:
var printChart = function macroCallBack(macro, args, chartInfo) {
document.getElementById("chartInfo").innerHTML=chartInfo;
var arLength=chartInfo.length;
console.log("arLength is: ",arLength);
for (var i=0; i<arLength; i++) {
console.log(chartInfo[i]);
}
}
And the console prints every character of the python list on a seperate line, like this:
[
"
2
0
1
5
etc...
I can't format the above console.log output, but every character is on a seperate line.
Also the length of the array is exactly the same as the length of the total string, so my conclusion is the python list is transformed to Javascript as one long string...
I hope someone can help me out!
You are right, you are looping through a string. This is because json are strings. This makes it pretty easy to pass data between different programming languages as strings are data types implemented in almost every programming language. However since it are strings you need to decode the string to a usable format/object. In javascript you can use the methodJSON.parse().
jsfiddle demo
var frompythonjsonstring ='["2015-03-22 06:43:02.000006", "2015-03-23 06:40:46", "2015-03-24 06:38:31.000001", "2015-03-25 06:36:15.000002", "2015-03-26 06:33:59.000003", "2015-03-27 06:31:44.000004", "2015-03-28 06:29:28.000005", "2015-03-29 07:27:13.000006", "2015-03-30 07:24:57", "2015-03-31 07:22:42.000001", "2015-04-01 07:20:27.000002", "2015-04-02 07:18:13.000003", "2015-04-03 07:15:58.000004", "2015-04-04 07:13:44.000005", "2015-04-05 07:11:31.000006", "2015-04-06 07:09:17", "2015-04-07 07:07:04.000001", "2015-04-08 07:04:52.000002", "2015-04-09 07:02:40.000003", "2015-04-10 07:00:28.000004"]';
macroCallBack(frompythonjsonstring);
function macroCallBack (str) {
obj = JSON.parse(str)
for (var i=0; i<obj.length; i++) {
console.log(obj[i]);
}
}
You should look at JSON.stringify and JSON.parse javascript methods that will turn string into Javascript objects. Hope this helps

Looping Through JSON

I have a JSON object:
var json = {"Mike":1, "Jake":1, "Henry":1};
I am trying to loop through this list to access the names. Currently I am using:
for (var name in json) {
if (json.hasOwnProperty(name)) {
console.log(name);
}
}
But it's not printing the name. Is that the correct way to do it?
jsFiddle: http://jsfiddle.net/bKwYq/
As other people mentioned, this is not JSON, it's just an object.
The hasOwnProperty thing may not really be necessary here also.
var persons = {"Mike":1, "Jake":1, "Henry":1};
for (var name in persons) {
alert(name);
}
This will work in every browser: http://jsfiddle.net/HsNMY/
It can be done by getting the key using Object.keys and then using foreach loop to print to console or display as alert message.
var persons = {"Mike":1, "Jake":1, "Henry":1};
var keysInPerson= Object.keys (persons);
keysInPerson.forEach ((name) => console.log (name));
//Alert
keysInPerson.forEach ((name) => alert (name));
The correct way to PRINT the name is to use document.write instead of console.log, as in this fiddle :
http://jsfiddle.net/jRAna/

Looping to Parse JSON Data

Description and Goal:
Essentially data is constantly generated every 2 minutes into JSON data. What I need to do is retrieve the information from the supplied JSON data. The data will changed constantly. Once the information is parsed it needs to be captured into variables that can be used in other functions.
What I am stuck in is trying to figure out how to create a function with a loop that reassigns all of the data to stored variables that can later be used in functions.
Example information:
var json = {"data":
{"shop":[
{
"carID":"7",
"Garage":"7",
"Mechanic":"Michael Jamison",
"notificationsType":"repair",
"notificationsDesc":"Blown Head gasket and two rail mounts",
"notificationsDate":07/22/2011,
"notificationsTime":"00:02:18"
},
{
"CarID":"8",
"Garage":"7",
"Mechanic":"Tom Bennett",
"notificationsType":"event",
"notifications":"blown engine, 2 tires, and safety inspection",
"notificationsDate":"16 April 2008",
"notificationsTime":"08:26:24"
}
]
}};
function GetInformationToReassign(){
var i;
for(i=0; i<json.data.shop.length; i++)
{
//Then the data is looped, stored into multi-dimensional arrays that can be indexed.
}
}
So the ending result needs to be like this:
shop[0]={7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18 }
shop[1]={}
You can loop through your JSON string using the following code,
var JSONstring=[{"key1":"value1","key2":"value2"},{"key3":"value3"}];
for(var i=0;i<JSONstring.length;i++){
var obj = JSONstring[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
//based on the result create as you need
}
}
Hope this helps...
It sounds to me like you want to extract the data in the "shop" property of the JSON object so that you can easily reference all of the shop's items. Here is an example:
var json =
{
"data":
{"shop":
[
{"itemName":"car", "price":30000},
{"itemName":"wheel", "price":500}
]
}
},
inventory = [];
// Map the shop's inventory to our inventory array.
for (var i = 0, j = json.data.shop.length; i < j; i += 1) {
inventory[i] = json.data.shop[i];
}
// Example of using our inventory array
console.log( inventory[0].itemName + " has a price of $" + inventory[0].price);
Well, your output example is not possible. You have what is a list of things, but you're using object syntax.
What would instead make sense if you really want those items in a list format instead of key-value pairs would be this:
shop[0]=[7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18]
For looping through properties in an object you can use something like this:
var properties = Array();
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties.push(propertyName);
}
}
Honestly though, I'm not really sure why you'd want to put it in a different format. The json data already is about as good as it gets, you can do shop[0]["carID"] to get the data in that field.

Categories