Link to Scrimba to check on code : https://scrimba.com/scrim/czvrQJcM
Essentially what should happen is that when the details are added and the button is clicked, the data first gets saved into the object, 'student' and pushed into the array. Then the array is run and the students names are displayed on the page.
I just solve your problem. Look:
At your enrolStudent() function you set the following line:
studentList = studentList.push(student);
So, you should change it to:
studentList.push(student);
This is because the push() method returns the length of the array. So, you don't need to attribute the operation result to the array. The method already updated its own value.
Task4 after the change:
function enrolStudent()
{
let firstnameRef = document.getElementById("fname");
let lastnameRef = document.getElementById("lname");
let studentIdRef = document.getElementById("studentid");
let dateRef = document.getElementById("date");
let courseRef = document.getElementById("course");
let genderRef = document.getElementsByName("gender");
for (let i=0; i < genderRef.length; i++)
{
if (genderRef[i].checked)
{
var genderSelection = genderRef[i];
}
}
let student = new Object();
student.firstName = firstnameRef.value;
student.lastName = lastnameRef.value;
student.id = studentIdRef.value;
student.course = studentIdRef.value;
student.gender = genderSelection.value;
student.date = dateRef.value;
studentList.push(student);
var val = studentList.push(student);
studentEnrolSummaryRef.innerHTML = displayStudents(studentList);
console.log(val);
}
```
I am trying to append an array to an array. I am expecting the output to be something like:
[[Dep,POR],[14073,99.25],[14072,0.06]]
But I am getting:
Dep,POR,14073,99.25,14072,0.06
Here's what I have so far:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = ['Dep','POR'];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_por = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(hist_por);
}
When you initialize hist_por, you want that to be a 2-D array whereas you currently have just a single array. So you would want to change its instantiation to:
hist_por = [['Dep','POR']]; // [[ ... ]] instead of [ ... ]
Also per #justrusty's answer, you need to JSON.stringify(hist_por) when you pass it to document.write(). This is the more important piece so his answer should be accepted.
So the whole code block would become:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = [['Dep','POR']];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_rop = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(JSON.stringify(hist_por));
}
This may help you https://codepen.io/anon/pen/xQLzXx
var arr = ['foo','bar'];
var arr2 = ['baz', 'boo']
arr.push(arr2);
console.log(arr);
document.write(arr);
document.write("<br>");
document.write(JSON.stringify(arr));
It's basically just the way it writes it to document. If you log it in console you'll see the array appended. Or if you JSON.stringify() first it will show as you expect.
My advice is ALWAYS console.log() so you can see exactly how the data is structured
The others have already pointed out what the problem is (+ there's a typo in one of your variable names - arr_rop vs arr_por). Here's an ES6 version that will break in older browsers, for learning purposes:
function get_historical() {
const well = document.getElementById('wellSelect');
const selected_well = well.options[well.selectedIndex].value;
const hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
const hist_por = Object.values(hist_json_obj).reduce(
(arr, item) => [...arr, [item.dep, +item.por]],
[["Dep", "POR"]]
);
document.write(JSON.stringify(hist_por));
}
I have 3 json files:
sources.json
destination_level1.json
destination_level0.json (final file)
I want to "merge" all theses files by replacing matching strings e.g
destination_level0 -> destination_level1 -> sources
in words: "Check the keys in destination_level0 e.g. "Element1", go to destination_level1 and look for a matching object and replace Element1 in destination_level0 with that object." Same goes on from destination_level1 to sources.
Sources might look like this:
{"john": ["A","B"],"mike": ["123","234","345"],"doe": ["abc","cde"],"ann": {"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]}}
destination_level_1 like this:
{"Element1": ["john","ann","john","john","doe","mike"],"Element2": ["ann","mike","ann","doe","doe","doe","ann"],"Element3": ["ann","doe","ann"]}
and destination_level_0 like this:
{"FinalA": ["Element1","Element2","Element1","Element2","Element2"],"FinalB": ["Element2","Element2","Element2","Element1"]}
The final result should look like this:
{"FinalA": [[["A","B"],{"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]},...
I have tried some lodash & underscore, but got stuck.
Any ideas?
Just in pure JavaScript
var sources = {"john": ["A","B"],"mike": ["123","234","345"],"doe": ["abc","cde"],"ann": {"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]}};
var destination_level_0 = {"FinalA": ["Element1","Element2","Element1","Element2","Element2"],"FinalB": ["Element2","Element2","Element2","Element1"]};
var destination_level_1 = {"Element1": ["john","ann","john","john","doe","mike"],"Element2": ["ann","mike","ann","doe","doe","doe","ann"],"Element3": ["ann","doe","ann"]};
var final = {};
for(var key in destination_level_0){
var preFinal = [];
var elems = destination_level_0[key];
for(var i in elems){
var elem = elems[i];
var names = destination_level_1[elem];
for(var j in names){
var name = names[j];
var finalItem = sources[name];
preFinal.push(finalItem);
}
}
final[key] = preFinal;
}
console.log(final);
console.log(JSON.stringify(final));
Map an item from level0 => level1 => level2 using Array#.map inside Array#map (or lodash's _.map()):
var level0 = {"FinalA": ["Element1","Element2","Element1","Element2","Element2"],"FinalB": ["Element2","Element2","Element2","Element1"]};
var level1 = {"Element1": ["john","ann","john","john","doe","mike"],"Element2": ["ann","mike","ann","doe","doe","doe","ann"],"Element3": ["ann","doe","ann"]};
var level2 = {"john": ["A","B"],"mike": ["123","234","345"],"doe": ["abc","cde"],"ann": {"abc": ["yxc","xcv","cvb"],"bcd": ["poi","iuz","uzt"]}}
;
var result = Object.keys(level0).reduce(function(r, key) {
r[key] = level0[key].map(function(element) {
return level1[element].map(function(item) {
return level2[item];
});
})
return r;
}, Object.create(null));
console.log(JSON.stringify(result));
How can we put data into multi dimensional array or json within a loop.
I know that it's possible to store multi dimensional data at one time, but I want it inside the loop as I have described in the code.
var sub_cat_checked_val = [];
sub_cat_checked.each(function (index) {
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
sub_cat_checked_val['key_one']['key_two']='value';
sub_cat_checked_val[sub_cat_id][index] = index:jQuery(this).val();
});
As it's possible in php like $var_name['key1']['key2']['keyn']='value';
sub_cat_checked_val[sub_cat_id] needs to be defined as an array, so add the lines:
if (!sub_cat_checked_val[sub_cat_id]) {
sub_cat_checked_val[sub_cat_id] = [];
}
to define the value as an array if it does not exist.
Try this snippet:
<script>
var k = {};
k.a = {};
k.a.b = {};
k.a.b.c = {};
k.a.b.c.d = 5;
console.log(k);
</script>
I was able to do it with all of you guys help with some of modifications.
Here is what I did:
sub_cat_checked.each(function (index) {
console.log(index_val);
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
console.log(sub_cat_id);
if (sub_cat_checked_val[sub_cat_id] == undefined) {
sub_cat_checked_val[sub_cat_id] = [];
}
sub_cat_checked_val[sub_cat_id][index] = jQuery(this).val();
});
Thanks a lot to all of you.
I'm new to HTML/javascript. I'm running a local server, with an html/javascript file and a separate python script.
Question: How do I pass a python array to javascript variable?
Work so far:
I've written the array to file data.txt:
1 32.1
2 10.0
but I could put it in JSON format if it's easier.
Here's my progress so far:
var x_pos = [];
jQuery.get('http://127.0.0.1:8000/data/data.txt',function(data){
// ??? Code here ???
});
console.log(x_pos[0])
Note: if there is a much simpler way to do this, I'm open to suggestion. Thanks.
var x_array = [];
var y_array = [];
jQuery.get('http://localhost/test/data.txt',function(data){
var lines = data.split(/\r\n|\n/g);
for (var i = 0; i < lines.length; i++) {
line = lines[i].split(/\s+/g);
x_array.push(line[0]);
y_array.push(line[1]);
}
console.log(x_array);
console.log(y_array);
});
Use JSON instead. Then you can just parse it as
jQuery.get('http://localhost/data.txt', function(data) {
var xy = JSON.parse(data);
});
and use as
alert(xy['1']); // or xy.propertyname if it is not-numeric
Your data structure would be like
{
"1": 32.1,
"2": 0
}
Just create a json structure for this and do a JSON.parse(data) after.
Here is your structure:
{x: [1,2,3,4], y:[32.1,10.0,76.3]}
One of the solutions is use split. It splits the string.
var newData = [];
data = data.split('\n');
data.forEach(function(entry){
entry = entry.split(' ');
newData.push({
x : entry[0],
y : entry[1]
});
});
console.log(newData);
You need to use regular expressions to parse the text file. You cannot just use JSON.parse() on a string that isn't in json format.
http://plnkr.co/edit/39aBGgwvNI7Lem6eiefu?p=preview
$.get("http://localhost/data.txt", parse);
function parse(str) {
var lineBreak = /\r\n/g;
var space = /\s/g;
var tmp = str.split(lineBreak).map(function(l) {
var split = l.split(space);
return { key: split[0], val: split[1] };
});
var data = JSON.stringify(tmp, null, 2);
$("#data").text(data);
}