How to access dictionary like structure in Protovis (Javascript) - javascript

I am trying to visualize a flickr dataset using protovis. I do understand the visualization part, but i have a question about accessing the data however. I was provided an example visualization and it accesses the data as folllowing:
var data = pv.range(250).map(function(row) {
return {
views: parseInt(Data.data(row, 2)), //refers to the 4 row and 2nd collumn in CSV
users: Data.data(row, 6),
date: Data.data(row, 8))), //more collumns excist but for now we only use these
};
});
As i understand a part of the data set is now stored in the variable data, namely views, users and date. Is this variable able to beaccessed like a dictionary?
What i am trying to do is checking whether there are date on which one user occurs more than 2 times. I thought of looping through the var data as follows:
dateUserDict {};
for (d=0; d < data.date.length; d++ ){
for (i=0; i < data.users.length; i++ ){
for (j=0; j < data.users.length; j++){
if (data.users[i] == data.users[j]){
userCounter++ //this should count the number of occurences of a specific user on a specific date
dateUserDict[data.date] = [data.user][userCounter]}
}
}
}
This does not seem to work. I am trying to store the events (the number of times a user occurs on a specific date) in a dictionary. If i get the dictionary as described i can easily visualise the whole thing. But it is this conversion from the first dict (data) to the second (dateUserDict) which bugs me!
Any help or a push is highly appreciated!
Thanks
jorrit

The function you provided will product a Javascript array of objects.
var data = pv.range(250).map(function(row) {
return {
views: parseInt(Data.data(row, 2)), //refers to the 4 row and 2nd collumn in CSV
users: Data.data(row, 6),
date: Data.data(row, 8))), //more collumns excist but for now we only use these
};
});
The result will look something like this:
var data = [ {views:10, users: 9, date: '09/13/1975'}, ... ]
So instead of using data.users.length, use data.length, and instead of data.users[i], you should be using data[i].users, etc.

Related

(JS) Google Script App Search / Filter for keyword

I have been stumped on this for a while. I am fairly new to Google script app and wanted to see if there is a way to make this happen. So far, I've used a few methods within Google Sheet but seem to not get it working.
The code below does give me an output of all the data, however, the data that is nested in the data.custom_fields[x] has multiple objects that is separated by ",". I would like to be able to filter out the other key words and just use whatever is inside "display_value=". The display_value= is not always in the same area so have to run a search for them.
I am assuming some kind of If statement would be used here..
An example of the object is:
{type=x, resource_subtype=x, created_by={name=x, gid=x, resource_type=x}, display_value=Cool Value, description=x, enabled=x, resource_type=custom_field, gid=x, enum_options=[x.lang.Object;x, enum_value={x}, name=x}
I've tried to split function as well but not sure how to filter out the words I need.
function Users() {
var options = {
"headers" : {
"Authorization": "API Key here"
}
}
var response = UrlFetchApp.fetch("URL here", options);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var sheet = ss.getSheetByName("Tab Name here"); // specific sheet name getSheetByName(""); alternatively use ss.getActiveSheet()
var dataAll = JSON.parse(response.getContentText()); //
var dataSet = dataAll.data; // "data" is the key containing the relevant objects
var rows = [],
data;
for (i = 0; i < dataSet.length; i++) {
data = dataSet[i];
rows.push([
data.gid,
data.name,
data.permalink_url,
data.due_on,
data.custom_fields[1],
data.custom_fields[2],
data.custom_fields[4],
data.custom_fields[5],
data.custom_fields[6],
data.custom_fields[7],
data.custom_fields[8],
data.custom_fields[9],
]); //your JSON entities here
}
// [row to start on], [column to start on], [number of rows], [number of entities]
dataRange = sheet.getRange(2, 1, rows.length, 12);
dataRange.setValues(rows);
Thank you in advance!
Example Image of JSON imported data
Although they appear separated by ,'s, that is only how they're displayed in the log. Because you're using JSON.parse, you're receiving/converting to an Object, not a string.
Because data.custom_fields is an array of objects, you can access the property/key values as : data.custom_fields[x].display_value.
Learn More:
JSON.parse()
Accessing Object Properties
If you want to extract display_value, try
let myVal = myData.match(/(?<=display_value=)[^,]+/g)[0]
I guess that myData could be data.custom_fields[5], so replace it by
data.custom_fields[5].match(/(?<=display_value=)[^,]+/g)[0]

How to create the data as an array of object with limit of 5 data in JavaScript

How to create the data as an array of objects with a limit of 5 data in JavaScript.
I am using web socket and getting this call first time
[
{city:"Newyork",value:10,"time":"13:8"},
{city:"London",value:20,"time":"13:8"}
]
Now In the second call, I will get data like that
[
{city:"Newyork",value:150,"time":"13:20"},
{city:"London",value:25,"time":"13:20"}
{city:"Sydney",value:20,"time":"13:20"}
]
So what I am doing here is I am adding new data and updating the existing data and then updating my state. Here is the code for that.
var city = this.state.city;
for(var j=0; j<res.length; j++){
const i = city.findIndex(_item => _item.city === res[j].city);
if (i > -1) city[i] = res[j]; // (2)
else city.push(res[j]);
}
this.setState({data:city})
This is working fine.
Now How I declare a state where I have to update five data which based on the last five WebSocket call.
Somewhat like this
myData = [{newyork:{[value:10,time:13:20],[value:150,time:13:20]}},London:{[value:20,time:13:20],[value:25,time:13:20]},Sydney:{[value:20,time:13:20]}];
So Based on this data I can plot a chart of a specific city. I need only 5 data of each city.
Can anyone help me here?
On each update, for each city, you can do something like this:
if(city[city_name].length >= 5){
city[city_name].shift();
}
city[city_name].push(new_city);

How do I omit the words "type" and "value" from showing in my google sheet after running google script to get user data from AD?

i am new to Javascript and im currently trying to create a google sheet that lists all the users in the AD group + their phone numbers. however when i run this script below, the cell that should have the phone number in it has, "type=work, value=(000)123-4567 as well. i just want the phone number to be displayed by itself. how would I work around this? I'm sure im missing something simple
function writeToSpreadsheet(){
var values = [];
var users = AdminDirectory.Users.list({domain:'companydomain.com'}).users;
for (var i=0; i<users.length; i++){
values.push([users[i].name.fullName, users[i].phones]);
var spreadsheetUrl = 'https://docs.userinfospreadsheet';
SpreadsheetApp.openByUrl(spreadsheetUrl).getSheets()[0].getRange(1, 1, values.length, values[0].length).setValues(values)
Im using this guide as a reference https://sites.google.com/site/scriptsexamples/home/announcements/listingdomainusernamesinaspreadsheet,
As the documentations states, phones is an array of objects. The simplest way of handling them would be to use a function that converts them into a string:
function generatePhonesCell(phones) {
return phones
.map(phone => {
const value = phone.value
const type = phone.type.replaceAll('_', ' ')
return `${value} (${type})`
})
.join('\n')
}
This will list the phones in the form:
(000)123-4567 (home)
(000)765-4321 (work)
You only need to add them into your existing code:
values.push([users[i].name.fullName, generatePhonesCell(users[i].phones || [])])
I think that user's phones property is not a string but rather an object or list.
In order to get the nice list of the phone numbers you have to replace users[i].phones pushed to values array with function call getPhones(users[i].phones)
And this function should be something like this:
If user phones are array of objects [{type: 'work', value: '(000)123-4567'}]:
function getPhones(arr) {
return arr.map(function(phoneObj) {
return phoneObj.value;
}).join(', ')
}
or if it is simply an object replce users[i].phones with users[i].phones.value

Get keys from javascript array

Hello i have selectbox to show from javascript array.
<h6><strong>Brand</strong></h6>
<select data-placeholder="Brand..." multiple id="brand" style="width:200px;height:50px;margin: 0;">
<script language="javascript">print_brand1("brand");</script>
</select>
But when i choose one of selectbox data then it get values. Here is javascript code
var brand_arr = new Array(
1:"Acer",
2:"Dell"
);
function print_brand1(brand_id){
var option_str = document.getElementById(brand_id);
option_str.length=0;
option_str.selectedIndex = 0;
for (var i=0; i<brand_arr.length; i++) {
option_str.options[option_str.length] = new Option(brand_arr[i],brand_arr[i]);
}
}
How do i get keys (not values) when i choose one of selectbox data?
Your code will not work in its current state, however if you insist on keeping your current array structure you would need:
var brand_arr = {
1: "Acer",
2: "Dell"
};
Which syntactically makes little sense, assigning a key of 1/2 makes little sense when you could just get this number by using the current index + 1.
Note that with the changes above, in order to assign the keys 1 and 2 we are having to iterate over a Javascript Object and not a Javascript Array.
If you wanted to print 1 and 2 you could then do:
for(var k in brand_arr) {
if(brand_arr.hasOwnProperty(k)) {
console.log(k); // key
console.log(brand_arr[k]); // value
}
}
Although this answers your problem, I would still consider the structure of your data, it would make much more sense to have something like:
var brand_arr = [
{ brand: 'Acer', price: 200 },
{ brand: 'Dell', price: 200 }
];
Note how in the above example we can add extra details about that brand in the JSON. We could then iterate over the brand array to get more detail about each brand in a much more readable format opposed to a user assigned index and its name.

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