Javascript turns array into string - javascript

I'm rewriting some Python code in javascript and I'm running into something strange. I'm sure I'm overlooking something stupid, but it appears that it's returning a comma-separated string where I expect an array.
python:
triples = [('one', 'two', 'three'), (...), ... ]
for w1, w2, w3 in triples:
key = (w1, w2)
if key in self.cache:
self.cache[key].append(w3)
else:
self.cache[key] = [w3]
returns:
('of', 'Thee,'): ['Sailing', 'Light'],
('meat', 'within'): ['is'],
javascript:
for (var i=0; i<=triples.length; i++) {
if (triples[i]) {
var key = [triples[i][0], triples[i][1]];
if (key in this.cache) {
this.cache[key].push(triples[i][2]);
} else {
this.cache[key] = [];
this.cache[key].push(triples[i][2]);
}
}
}
returns:
'you,estimated,': [ 'and', 'and' ],
'estimated,,and': [ 'far', 'far' ],

Related

How can I access to each field of a json object?

I have used csvtojson in order to write the csv data into a sql database, the object that the funcion return to have this structure:
var prueba = [
{'Aula;Capacidad': 'A10+11;112'},
{'Aula;Capacidad': 'A12;66' }
];
How can I acces to each field? I am trying to do console.log(prueba[0]["Capacidad"]) in order to see if it is running but it prints "undefined".
'Aula;Capacidad' is seen as a key, so you only can do the following:
console.log(prueba[0]["Aula;Capacidad])
which will write
A10+11;112
to the console.
Your properties are actually named 'Aula;Capacidad', meaning you'd need to use prueba[0]['Aula;Capacidad'] to get the value you are looking for.
This is what you need to iterate through the list of items:
var prueba = [{'Aula;Capacidad': 'A10+11;112'},{'Aula;Capacidad': 'A12;66' }];
for (var i = 0; i < prueba.length; i++) {
console.log(prueba[i]);
}
If you need to go deeper and iterate over every item properties:
var prueba = [{'Aula;Capacidad': 'A10+11;112'},{'Aula;Capacidad': 'A12;66' }];
for(var i = 0; i < prueba.length; i++) {
for(var p in prueba[0]) {
console.log(p, prueba[i][p]);
}
}
Your key you are looking up is in a composite key. So you would need to look it up with that composite key and than split it.
var prueba = [
{'Aula;Capacidad': 'A10+11;112'},
{'Aula;Capacidad': 'A12;66' }
];
console.log(prueba[0]['Aula;Capacidad'].split(";")[1]);
Other choice is to parse it all and look it up by the key.
var prueba = [
{'Aula;Capacidad': 'A10+11;112'},
{'Aula;Capacidad': 'A12;66' }
];
const parsed = prueba.reduce(function (arr, row) {
const entry = Object.entries(row)[0];
const keys = entry[0].split(";");
const values = entry[1].split(";");
const data = keys.reduce(function (o, key, index) {
o[key] = values[index];
return o;
}, {});
arr.push(data);
return arr;
}, []);
console.log(parsed[0].Capacidad);
console.log(parsed[1].Capacidad);
Your data looks malformed so you might need to do some manual processing.
You have an array of two items, both with a single key-value in them. You can do console.log(prueba[0]["Aula;Capacidad"]) and this will return 'A10+11;112'.
You might need to split things by the ; there so you could do something like this:
var prueba = [
{'Aula;Capacidad': 'A10+11;112'},
{'Aula;Capacidad': 'A12;66' }
];
prueba.forEach(item => {
const splitItem = item["Aula;Capacidad"].split(";");
console.log("Each item now looks like this: " + splitItem)
// You can access the first and second part of the item like this
console.log(splitItem[0], splitItem[1])
})
To be honest, I'd go back and look at how this data is being added to your DB. It looks messed up.

Accessing objects and sorting with multiple conditions

ARRAYS:Accessing objects and sorting in JavaScript with multiple conditions.
HI i am very new to javascript so it might seem very basic question.
i have to sort according to the status field..
var issues = cf.getEventMessage(reply); //issues has all the data
var assigneeTasks = {};
for(var i=0;i<issues.length ;i++){
var record = issues[i];
if(assigneeTasks[record.assigneemail] == undefined){
assigneeTasks[record.assigneemail] = [];
}
assigneeTasks[record.assigneemail].push(record); //sorted according to assigneemail
}
now assigneeTasks has
{"dev#vtu.com":
[
{"id":"T-728","assignedTo":"dev","assigneemail":"dev#inchfactory.com","duedate":"2017-09-29","status":"Open"},
{"id":"T-727","assignedTo":"dev","assigneemail":"dev#inchfactory.com","duedate":"2017-09-29","status":"In Progress"},
{"id":"T-726","assignedTo":"dev","assigneemail":"dev#inchfactory.com","duedate":"2017-10-04","status":"Open"},
{"id":"T-679","assignedTo":"devt","assigneemail":"dev#inchfactory.com","duedate":"2017-09-29","status":"Under Review"},
{"id":"T-645","assignedTo":"dev","assigneemail":"dev#inchfactory.com","duedate":"2017-09-27","status":"In Progress"}
],
"paul#vtu.com":
[
{"id":"T-728","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-09-29","status":"Open"},
{"id":"T-727","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-09-29","status":"In Progress"},
{"id":"T-726","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-10-04","status":"Open"},
{"id":"T-679","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-09-29","status":"Under Review"},
{"id":"T-645","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-09-27","status":"In Progress"}
]
}
What I want is
{"dev#vtu.com":
[
{"id":"T-728","assignedTo":"dev","assigneemail":"dev#inchfactory.com","duedate":"2017-09-29","status":"Open"},
{"id":"T-726","assignedTo":"dev","assigneemail":"dev#inchfactory.com","duedate":"2017-10-04","status":"Open"},
{"id":"T-727","assignedTo":"dev","assigneemail":"dev#inchfactory.com","duedate":"2017-09-29","status":"In Progress"},
{"id":"T-645","assignedTo":"dev","assigneemail":"dev#inchfactory.com","duedate":"2017-09-27","status":"In Progress"}
{"id":"T-679","assignedTo":"devt","assigneemail":"dev#inchfactory.com","duedate":"2017-09-29","status":"Under Review"},
],
"paul#vtu.com":
[
{"id":"T-728","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-09-29","status":"Open"},
{"id":"T-726","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-10-04","status":"Open"},
{"id":"T-727","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-09-29","status":"In Progress"},
{"id":"T-645","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-09-27","status":"In Progress"}
{"id":"T-679","assignedTo":"paul","assigneemail":"paul#inchfactory.com","duedate":"2017-09-29","status":"Under Review"},
]
}
to sort array in object values you can use this code, if you want to sort based on number in id
function num(string) {
return parseInt(id.replace(/[^0-9]+/g, ''));
}
function compare(a, b) {
a = num(a.id);
b = num(b.id);
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
Object.keys(obj).forEach(function(key) {
output[key].sort(compare);
});
if you want to also sort based on date you need to incorporate answer to this question Sort Javascript Object Array By Date

Assign conditions/categories to elements in array

I have an array of words - my stimuli - and they are presented on the screen. Yet, each word has another "condition", that is they are either, say categoryA, categoryB, or categoryC. This is probably simple, but I couldn't find an answer and am stuck with it.
My final aim is to assign the categories randomly to the stimuli each time the script is run.
var stim = [ "AEROPLANE", "TRAIN", "CAR", "BIKE", "WALKING"];
Here I'd like AEROPLANE to have categA, TRAIN categB, and the rest categC.
I thought about something like this (or with integers instead of Letters):
var stim = [ ["AEROPLANE", A], ["TRAIN", B], ["CAR", C], ["BIKE", C], ["WALKING",C] ];
But this doesn't work. If I have categories, how would I access them to code responses?
This is the script that presents the stimuli (on each keypress a new one):
$(function(){
$(document).keypress(function(e){
if ($(e.target).is('input, textarea')) {
return;
};
if (e.which === 97 || e.which === 108) {
new_word = w_stim[Math.floor(Math.random() * stim.length)];;
$("#abc").text(new_word);
};
});
});
Make an array of objects:
var stim = [
{name:"AEROPLANE", category:"A"},
{name:"TRAIN", category:"B"},
{name:"CAR", category:"C"},
{name:"BIKE", category:"C"},
{name:"WALKING",category:"C"}
];
Then access the objects like:
stim[i].name
stim[i].category
JS Fiddle: http://jsfiddle.net/pJ6X2/
Another option would be
var stim = {
'A': ['AEROPLANE'],
'B': ['TRAIN'],
'C': ['CAR', 'BIKE', 'WALKING']
}
var items = stim[categoryChar];
if (undefined === items)
console.log('no such category');
else
console.log(items[Math.floor(Math.random() * items.length)]);

convert json string to csv using javascript

I have seen some of the posts for converting json to csv
for example 'http://jsfiddle.net/FLR4v/'.
I could not make them to convert this json to csv .
Here is my code (this works well but does not work with commented out var json3 below)
<html>
<head>
<title>JSON to CSV</title>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
//var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
var json3 = { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ], ] }
DownloadJSON2CSV(json3.data);
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
line += array[i][index] + ',';
}
// Here is an example where you would wrap the values in double quotes
// for (var index in array[i]) {
// line += '"' + array[i][index] + '",';
// }
line.slice(0,line.Length-1);
str += line + '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + escape(str))
}
</script>
</head>
<body>
<h1>This page does nothing....</h1>
</body>
</html>
The above code works ok.
What I need is the above needs to work with the below
var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
Thanks for your help
You still haven't explained clearly what your desired output is ("CSV" is too vague, especially when your original jsfiddle produced semicolon separated output).
But you do seem to be saying that your code works if you take this object:
var json3 = { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ], ] }
...as input to your function as follows:
DownloadJSON2CSV(json3.data);
But now you want to deal with an input object that has a slightly different structure, essentially the same thing but with an extra "wrapping" layer around your original structure:
var json3 = { "inp1:val1": { "data": [ [ 1378267200000, 0.0743 ], [ 1378270800000, 0.1787 ] ] }}
If I've summed up your question accurately, here's what you need:
DownloadJSON2CSV(json3["inp1:val1"].data);
This calls your function passing the array of arrays referenced by the "data" property of the object referenced by the "inp1:val1" property of the outermost object.
(Note that what you are calling "json" is not json at all, it is an object that happens to be created using JS's object literal syntax.)
Homework for you: read the MDN article Working With Objects.

IE 8 Array iteration

Hi I'm debugging my page for IE8 compat mode, and this script just doesn't like to work and crushes.
Basically it had to iterate through a 3D array, and add a local path to a variable. Well I could do it otherwise, but I'm just curious why the ** it never works...
Any suggestions are welcome :) Here's the code:
for(i=0;i<menu_items_p.length;i++)
for(j=0;j<menu_items_p[i].length;j++)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
and the array looks something like this:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
The problem though is that it sometimes have empty values, and array.length triggers some error...
When used your original array declaration:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
error occurs in IE8 but not in IE9. Just remove two commas:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'] // here comma removed
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'] // here comma removed
]
]
and all must work fine.
Maybe your code could handle empty values this way:
for(var i = 0; i < menu_items_p.length; i++) {
// we skip the value if it is empty or an empty array
if(!menu_items_p[i] || !menu_items_p[i].length) continue;
for(var j = 0; j < menu_items_p[i].length; j++) {
// again, we skip the value if it is empty or an empty array
if(!menu_items_p[i][j] || !menu_items_p[i][j].length) continue;
menu_items_p[i][j][1] = 'http://127.0.0.1/' + menu_items_p[i][j][1];
}
}
AS suggested by Yoshi and ThiefMaster, I made it following, and this is what solved it:
for(var i=0;i<menu_items_p.length;i++)
if (menu_items_p[i] !== undefined)
for(var j=0;j<menu_items_p[i].length;j++)
if (menu_items_p[i][j] !== undefined)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
Global vars replaced.
Check for undefined.
It's a pity they didn't answer in a formal way, so I would have to answer my self :)
Thanks everyone!

Categories