Javascript object key is not accessible - javascript

I am using the Samsung Tizen SDK for SmartTV app development. I have some code that converts CSV to a Javascript object. I am having problems accessing one of the keys in the object that is created from the code.
Code:
function csvJSON(csv) {
var lines = csv.split("\n");
var result = [];
var headers = lines[0].split(",");
for (var i = 1; i < lines.length; i++) {
var obj = {startTime:'',
endTime:'',
day:''};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
return result; // JavaScript object
}
My inputs to this function look like:
Input to function
While debugging the return result line in the console developer mode (I set a local watch of obj.endTime), I cannot access the endTime key, despite it showing up in the debugger. It is almost as if a special character is involved somehow.
endTime key
I tried the same snippet of code in jsFiddle and it worked ... so it seems like something related to the version of Javascript/ECMAScript that is running on the Tizen Emulator. Perhaps this was an issue in earlier versions of Javascript ?
Thanks!

I would check that endTime in your csv header is truly equal to endtime, i.e.
endTime1 = 'endTime'
endTime2 = '\uff45ndTime'
console.log(`${endTime1} equals ${endTime2} is ${endTime1 === endTime2}`)
// endTime equals endTime is false
obj = {}
obj[endTime1] = 'endTime1'
obj[endTime2] = 'endTime2'
console.log(obj)
// {
// "endTime": "endTime1",
// "endTime": "endTime2"
// }
Any reason why you are not using a library for this?, e.g.
http://papaparse.com/docs#csv-to-json

Related

Google Scripts let returns "missing ; before statement", the same code ok when using var

The code below works in one sheet, but returns error in another: "Missing ; before statement".
Occurs on the line
let e = events[i];
So basically, code is ok as it works in one sheet. But in another sheet it works only if using
var e = events[i];
It works anyway, but of course, would be nice to know why? Most probably some sheet setting or something I'm missing here?
function getHolidays() {
var startTime = new Date(2020,1-1,1);
var endTime = new Date(2020,12-1,31);
var calendarChoice = 'sl.slovenian#holiday#group.v.calendar.google.com';
var calendar = CalendarApp.getCalendarById(calendarChoice);
var events = calendar.getEvents(startTime, endTime);
var data = [];
for (var i = 0; i < events.length; i++)
{
let e = events[i];
data.push([e.getStartTime(), e.getTitle(), e.getDescription(), e.getAllTagKeys().join(',')]);
}
var s = SpreadsheetApp.getActive().getSheetByName('Google Calendar + Script');
s.getRange(2, 7, data.length, 4).setValues(data)
}
It's very likely that the script project given the error is set to use the old runtime (Rhino) instead of the new runtime (Chrome V8) as th old runtime doesn't support let.
Possible solution: Enable the new runtime.
Related
Declaring variables on Google sheet script editor using let
Google App Script don't known native Javascript anymore?? let, includes(), Object.Values()

Reason why this for loop isn't working in JavaScript when hardcoding worked fine?

Previously, I was hardcoding
// weekdays_row.insertCell(0).innerHTML = "Su";
// weekdays_row.insertCell(1).innerHTML = "Mo";
// weekdays_row.insertCell(2).innerHTML = "Tu";
// weekdays_row.insertCell(3).innerHTML = "We";
// weekdays_row.insertCell(4).innerHTML = "Th";
// weekdays_row.insertCell(5).innerHTML = "Fr";
// weekdays_row.insertCell(6).innerHTML = "Sa";
So, I wanted to make a for loop,
var weekdays = ["Sun","Mon","Tues","Wed","Th","Fri","Sat","Sun"];
for (int i=0; i<6; i++) {
weekdays_row.insertCell(i).innerHTML = weekdays[i];
}
which led my very simple web app to crash. Any ideas why this isn't working? Sorry if it's very simple; I'm new to JavaScript!
Seems like your issue is about that i variable is typed as int, so JS is not a typed language, so you don't need to define its variable type, so try to replace the int i = 0 to let i = 0, that should work.
Problem is with the DataType you are using, you can declare a variable using let or var or const in javascript
for (let i=0; i < weekdays.length; i++) {
weekdays_row.insertCell(i).innerHTML = weekdays[i];
}
int type is not a valid javascript variable declaration method, use let or var or const
variables w3 schools

How to create a variable by setting a custom identifier as variable name

This looks crazy but it was a much-needed solution for my application to solve the problem of dynamic initialization...
when I inject the services dynamically I would like it to be identified by my own variable which matches the service.
Here is what >I want.
$rootScope.arr = ['MasterLookupService', 'PrinterService'];
for (i = 0; i < arr.length; i++) {
var arr[i] = $injector.get(arr[i]);
}
// it will end up something like this
var MasterLookupService = $injector.get('MasterLookupService');
I tried but none helped
// $rootScope.customObj = {
// MasterLookUpService: $injector.get('MasterLookupService'),
// PrinterService: $injector.get('PrinterService')
// }
I'm not sure about Jquery but this might be what I understand you need.
var arr = ['MasterLookupService', 'PrinterService'];
for(var i =0 ;i < arr.length; i++){
var varname = arr[i];
window[varname] = 'value '+i;
}
alert(MasterLookupService);
window object represents a window containing a DOM document. You may use other object depending upon your environment.

javascript conditions applied on independant objects

I'm going crazy for i do not understand the behavior of my loop!
here a sample of a json I read :
[{"type":"robot","town":"NANTES","region":"Ouest","performances":[{"date":YYYY-MM-DD","value":100},{...}],"availability":[{"date":"YYY-MM-DD","value":100},{...}]},{"type":"robot","town":"RENNES","region":"Ouest","performances":[{"date":YYYY-MM-DD","value":100},{...}],"availability":[{"date":"YYY-MM-DD","value":100},{...}]}
I create 2 objects :
REGIONS = {},TOWNS= {};
here is the function the moment i recieve the object:
function getRobotsDatas(robotList) {
for (var i = 0; i < robotList.length; i++) {
var robot = robotList[i];
// working on TOWNS object
//I check if the "town" object of TOWNS object already exist
if (TOWNS[robot.town] === undefined) {
// if not, i create it
TOWNS[robot.town] = {};
//then i push performances datas of my robot in my TOWNS.town object
TOWNS[robot.town].performances = robot.performances;
// the same for availability datas
TOWNS[robot.town].availability= robot.availability;
}
// then I work nearly the same way on REGIONS object.
//i check if the "region" object exist in REGIONS object. If not, i create it and add the perf+availability datas of the robot.
if (REGIONS[robot.region] === undefined) {
REGIONS[robot.region] = {};
REGIONS[robot.region].performances = robot.performances;
REGIONS[robot.region].availability= robot.availability;
}
// If the REGIONS.region already exist, i just want to add the datas of performances and availability in the already existing arrays of REGIONS.region (performances[] and availabilities[])
else {
for (var j = 0; j < robot.performances.length; j++) {
REGIONS[robot.region].performances.push(robot.performances[j]);
}
for (var k = 0; k < robot.availability.length; k++) {
REGIONS[robot.region].availability.push(robot.availability[k]);
}
}
}
The problem is that the condition for an already existing "REGIONS.region" is also applied on TOWNS. It adds values of performances and availabilities in the TOWNS objects of the robots which have the same value of the "region" attribut.
for example, in the sample i gave at the beginning, i'll find availabilities and perf datas in a new object : REGIONS.Ouest {performances:[...], availability:[...]}, but i will also find NANTES' perf an availibilities datas in RENNES' perf and availabilities arrays... and THAT, i don't want!
What's wrong with my condition / loop!???
Your code refers to 'town' but your incoming JSON has 'ville' instead.
I appreciate that this won't fix the problem, but the example should at least be correct.
The incoming JSON has two sub-objects. For each one, you test for presence in your Towns and Regions data structures. If they don't each have a matching entry, you are creating one, and then adding entries in the two further sub-objects (performances and availability).
If you don't want this in both cases, you need to test the incoming JSON appropriately.
This is a problem of variable Reference. try this simple change JSON.parse(JSON.stringify(xxx))
function getRobotsDatas(robotList) {
for (var i = 0; i < robotList.length; i++) {
var robot = robotList[i];
if (TOWNS[robot.town] === undefined) {
TOWNS[robot.town] = {};
TOWNS[robot.town].performances = JSON.parse(JSON.stringify(robot.performances));
TOWNS[robot.town].disponibilite = JSON.parse(JSON.stringify(robot.availability));
}
if (REGIONS[robot.region] === undefined) {
REGIONS[robot.region] = {};
REGIONS[robot.region].performances = robot.performances;
REGIONS[robot.region].availability= robot.availability;
}
else {
for (var j = 0; j < robot.performances.length; j++) {
REGIONS[robot.region].performances.push(robot.performances[j]);
}
for (var k = 0; k < robot.availability.length; k++) {
REGIONS[robot.region].availability.push(robot.availability[k]);
}
}
}
}
JS is funny.... :)

JSON stringification turns 47 byte json string to 340mb?

var keys = [7925181,"68113227"];
var vals = {"7925181":["68113227"],"68113227":["7925181"]};
var temp = [];
for (var i = 0; i < keys.length; i++) {
temp[keys[i]] = vals[keys[i]];
}
//alert(JSON.stringify(vals).length);
alert(JSON.stringify(temp).length);
When I run that script in Chrome I get, after a good amount of time, an output of 340666156.
My question is... how?
The commented out alert outputs 47. Seems to me that the second alert should yield the same result? That temp should pretty much be an exact copy of val?
The jsfiddle of it:
http://jsfiddle.net/vMMd2/
Oh - and if you want to crash your browser window (well it crashed my Google Chrome window) just add the following to the end:
temp.forEach(function(entry) {
alert(temp);
});
Any ideas?
var keys = [7925181,"68113227"];
var vals = {"7925181":["68113227"],"68113227":["7925181"]};
var temp = {}; // <--- !!!
for (var i = 0; i < keys.length; i++) {
temp[keys[i]] = vals[keys[i]];
}
//alert(JSON.stringify(vals).length);
alert(JSON.stringify(temp).length);
http://jsfiddle.net/zerkms/vMMd2/2/
You're creating a sparse array, and presumably V8 initializes all the gaps with some garbage null undefined values (thanks to nnnnnn for checking that). It takes some time
#zerkms, is right. But I also wanted to pointed out why this is happening.
> var temp = [];
> temp[10] = 'test';
> temp
[ , , , , , , , , , , 'test' ]
As you can see, it creates 9 undefined values. I ran the above with nodejs so the null values are not showing up.
If I did JSON.stringfy() then you would see:
> JSON.stringify(temp)
'[null,null,null,null,null,null,null,null,null,null,"test"]'

Categories

Resources