How to convert a nested array in javascript to json structure - javascript

In the following code i am trying to populate the javascript class,such that i get an object which i can stringify to json string.
function classValue(valuearrs) {
for (var i = 0; i < valuearrs.length; i++) {
for (j = 0; j < valuearrs[i].length; j++) {
this.id = valuearrs[i][j];
this.name = valuearrs[i][j];
this.somekey = valuearrs[i][j];
}
}
}
function CreatenestedarrObj( valuearr) {
this.Arrayparameters = [new classValue (valuearr)];
}
function ArrayMethodCall() {
var valuearr = new Array();
valuearr[0] = "myval1";
valuearr[1] = "myval2";
valuearr[2] = "myval3";
var valuearr1 = new Array();
valuearr1[0] = "myval11";
valuearr1[1] = "myval12";
valuearr1[2] = "myval13";
nestedarr = new Array();
nestedarr[0] = valuearr;
nestedarr[1] = valuearr1;
var x = new CreatenestedarrObj( nestedarr);
var strobject = JSON.stringify(x);
alert(strobject);
}
</script>
</head> <body> MethodCall: <input type="button" value="Call Method" onclick=" ArrayMethodCall ()" />
After Stringifying the value expected is {ArrayParameters:[{myval1,myval2,myval3},{myval1,myval12,myval13}]}.The thing i can think i am missing is creating new object each time in the loop but how ? or i might be totally wrong.Any help will be much appreciated.

try this
function classValue(valuearrs) {
var arr = []
for (var i = 0; i < valuearrs.length; i++) {
for (j = 0; j < valuearrs[i].length; j++) {
var temp = new Object();
temp.id = valuearrs[i][j];
temp.name = valuearrs[i][j];
temp.somekey = valuearrs[i][j];
arr[j] = temp;
}
}
return arr;
}

Change this:
function classValue(valuearrs) {
var arr=[]
for (var i = 0; i < valuearrs.length; i++) {
arr[i]={};
for (j = 0; j < valuearrs[i].length; j++) {
arr[i].id = valuearrs[i][j];
arr[i].name = valuearrs[i][j];
arr[i].somekey = valuearrs[i][j];
}
}
return arr;
}

i don't know why you need to split the nestedarr to id,name and somekey
but if you don't need to, just return the valuearrs and you will be fine:
function classValue(valuearrs) {
return valuearrs;
}
function CreatenestedarrObj( valuearr) {
this.Arrayparameters = [new classValue (valuearr)];
}
function ArrayMethodCall() {
var valuearr = new Array();
valuearr[0] = "myval1";
valuearr[1] = "myval2";
valuearr[2] = "myval3";
var valuearr1 = new Array();
valuearr1[0] = "myval11";
valuearr1[1] = "myval12";
valuearr1[2] = "myval13";
nestedarr = new Array();
nestedarr[0] = valuearr;
nestedarr[1] = valuearr1;
var x = new CreatenestedarrObj( nestedarr);
var strobject = JSON.stringify(x);
console.info(strobject);
}
the output is
{"Arrayparameters":[[["myval1","myval2","myval3"],["myval11","myval12","myval13"]]]}
or far better if you don't want it as Arrayparameters, you can use following code
var strobject = JSON.stringify(nestedarr);
and the output will be like this :
[["myval1","myval2","myval3"],["myval11","myval12","myval13"]]

Related

Setting Double Array Values

I'm getting an error when I'm trying to assign values to an empty 2D array.
It says Cannot set property '0' of undefined.
Why is this and how can I fix it so that I can assign values from a 2D array to a new empty 2D array?
var array = await data;
array = JSON.parse(array);
var activeArray = new Array();
var inactiveArray = new Array();
for (let i = 0; i < array.length; i++)
{
if (array[i][2] == "Active")
{
activeArray[i][0] = array[i][0];
activeArray[i][1] = array[i][1];
activeArray[i][2] = array[i][2];
}
else
{
inactiveArray[i][0] = array[i][0];
inactiveArray[i][1] = array[i][1];
inactiveArray[i][2] = array[i][2];
}
}
This effectively solved my problem.
var array = await data;
array = JSON.parse(array);
var activeArray = new Array();
var inactiveArray = new Array();
var activeArrayCounter = 0;
var inactiveArrayCounter = 0;
for (let i = 0; i < array.length; i++)
{
if (array[i][2] == "Active")
{
activeArray[activeArrayCounter] = new Array();
activeArray[activeArrayCounter][0] = array[i][0];
activeArray[activeArrayCounter][1] = array[i][1];
activeArray[activeArrayCounter][2] = array[i][2];
activeArrayCounter++;
}
else
{
inactiveArray[inactiveArrayCounter] = new Array();
inactiveArray[inactiveArrayCounter][0] = array[i][0];
inactiveArray[inactiveArrayCounter][1] = array[i][1];
inactiveArray[inactiveArrayCounter][2] = array[i][2];
inactiveArrayCounter++;
}
}

Multidimentioanal arrays in JavaScript values not appending

I am trying to add values in a multidimensional array in JavaScript, but it doesn't seem to work. I get "variable not defined" error in snippet but can't see any variable which is not defined.
Does anyone have any idea what's going wrong here?
Many Thanks,
Hassam
var abc = "11:00, 11:10, 12:20,12:30";
var split = abc.split(",")
var limits = new Array();
var alltimes = [[],[]];
//var split = ["11:00", "11:10", "12:20","12:30"];
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
// alert(split.length );
if(i%2 === 1) // If odd value
{
alert(limits);
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
// alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
This is my JavaScript code
$(document).ready(function(){
$('.timepicker').click(function(){
var ajaxurl = 'Ajax.php',
data = {'action': 'Hassam'};
$.post(ajaxurl, data, function (response) {
// $('#timepicker').timepicker('option', 'disableTimeRanges', [abc]);
var split = response.split(",");
var x = 0;
for (var i = 0; i < split.length -1 ; i++) {
limits.push(split[i]);
alert(split.length );
if(i%2 === 1) // If odd value
{
for (var j = 0;j<2; j++)
{
// alert(limits[j]);
alltimes[x][j] = limits[j];
}
limits.length = 0;
x++;
}
alert(split.length + 2);
//
}
alert(alltimes);
// console.log(abc)
});
There is very simple solution to achieve what you want.
var split = ["11:00", "11:10", "12:20", "12:30"];
var alltimes = [];
while (split.length) {
alltimes.push(split.splice(0, 2));
}
console.log(alltimes);

How do I get JavaScript to recognize whether an object is in an array?

New to JavaScript objects. In the code below, I'm able to create and populate a list of book objects that each person has "checked out". However I am unable to "return" the books because I can't get seem to identify which patron's array the book is "checked out" in. I'm using
if (object in array) . . .
I got this from one of the previous answers. The statement block with the if never executes. Thanks for your help!
function Book(title, pub_date, call_number, authors){
this.title = title;
this.availability = true;
this.pub_date = pub_date;
this.current_date = null;
this.check_out_date = null;
this.call_number = call_number;
this.authors = authors;
}
Book.prototype.checkOut = function(){
this.availability = false;
var rdom = (Math.random() * 31 +1).toFixed(0);
var current_date = new Date();
this.check_out_date = new Date(current_date - rdom*24*3600*1000);
}
Book.prototype.checkIn = function(){
this.availability = true;
}
Book.prototype.isOverdue = function(){
var current_date = new Date();
if ((current_date - this.check_out_date)/1000/3600/24 > 14)
return true;
else
return false;
}
function Author(first_name, last_name){
this.first_name = first_name;
this.last_name = last_name;
}
function Patron(firstname, lastname, lib_card){
this.firstname = firstname;
this.lastname = lastname;
this.lib_card = lib_card;
this.books_out = [];
this.fine = 0;
}
Patron.prototype.readBook = function(book){
this.books_out.push(book);
}
Patron.prototype.returnBook = function(book){
this.books_out.pop(book);
}
var redAuthors, blueAuthors, greenAuthors, yellowAuthors, purpleAuthors
var redAuthor1 = new Author('John', 'Smith');
var redAuthor2 = new Author('James', 'Sullivan');
var redAuthors = [redAuthor1, redAuthor2];
var blueAuthors = greenAuthors = yellowAuthors = purpleAuthors = redAuthors;
redBook = new Book('Lakes', 1963, 456789, redAuthors);
blueBook = new Book('Rivers', 1964, 123456, blueAuthors);
greenBook = new Book('Streams', 1965, 234567, greenAuthors);
yellowBook = new Book('Ponds', 1966, 345678, yellowAuthors);
purpleBook = new Book('Brooks', 1967, 567891, purpleAuthors);
var catalog = [redBook, blueBook, greenBook, yellowBook, purpleBook]
var patron1 = new Patron('Sally', 'Hudson', '1');
var patron2 = new Patron('Rachel', 'Hung', '2');
var patron3 = new Patron('Andy', 'Cunningham', '3');
var patron4 = new Patron('Steve', 'Cote', '4');
var patron5 = new Patron ('Ted', 'Mitrou', '5');
var patrons = [patron1, patron2, patron3, patron4, patron5]
for (var day_count = 0; day_count < 10; day_count++){
for (var book_count = 0; book_count < 5; book_count++){
if (catalog[book_count].availability == true){
for (var pat_count = 0; pat_count < 5; pat_count++){
if (patrons[pat_count].books_out.length <= 1){
catalog[book_count].checkOut();
patrons[pat_count].readBook(catalog[book_count]);
break;
}
else
continue;
}
}
else {
catalog[book_count].checkIn();
for (pat_counter = 0; pat_counter < 5; pat_counter++){
if (catalog[book_count] in patrons[pat_counter].books_out){
if (catalog[book_count].isOverdue)
patrons[pat_counter].fine += 5;
patrons[pat_counter].books_out.returnBook(catalog[book_count]);
}
}
}
}
}
for (var k = 0; k < 5; k++){
console.log("Patron: " + patrons[k].firstname + " " + patrons[k].lastname);
console.log("Books checked out: ")
for (l = 0; l < patrons[k].books_out.length; l++) {
console.log(patrons[k].books_out[l].title);
}
console.log("Fine: $" + patrons[k].fine);
console.log();
}
You can use indexOf:
if (array.indexOf(object) > -1)
x in y would only return true if x is a string containing the name of a property on y.

JS missing ) in parenthetical (line #88)

I'm writing a program in JS for checking equal angles in GeoGebra.
This is my first JS code, I used c# formerly for game programming.
The code is:
var names = ggbApplet.getAllObjectNames();
var lines = new Set();
var angles = new Set();
var groups = new Set();
for(var i=0; i<names.length; i++)
{
if(getObjectType(names[i].e)==="line")
{
lines.add(names[i]);
}
}
for(var i=0;i<lines.size;i++)
{
for(var j=0;j<i;j++)
{
var angle = new Angle(i,j);
angles.add(angle);
}
}
for(var i=0;i<angles.size;i++)
{
var thisVal = angles.get(i).value;
var placed = false;
for(var j=0;j<groups.size;j++)
{
if(groups.get(j).get(0).value===thisVal)
{
groups.get(j).add(angles.get(i));
placed = true;
}
}
if(!placed)
{
var newGroup = new Set();
newGroup.add(angles.get(i));
groups.add(newGroup);
}
}
for(var i=0;i<groups.size;i++)
{
var list="";
for(var j=0;j<groups.get(i).size;j++)
{
list = list+groups.get(i).get(j).name;
if(j != groups.get(i).size-1)
{
list = list+",";
}
}
var comm1 = "Checkbox[angle_{"+groups.get(i).get(0).value+"},{"+list+"}]";
ggbApplet.evalCommand(comm1);
var comm2 = "SetValue[angle_{"+groups.get(i).get(0).value+"}+,0]";
ggbApplet.evalCommand(comm2);
}
(function Angle (i, j)
{
this.lineA = lines.get(i);
this.lineB = lines.get(j);
this.name = "angleA_"+i+"B_"+j;
var comm3 = "angleA_"+i+"B_"+j+" = Angle["+this.lineA+","+this.lineB+"]";
ggbApplet.evalCommand(comm3);
var val = ggbApplet.getValue(this.name);
if(val>180)
{val = val-180}
this.value = val;
ggbApplet.setVisible(name,false)
});
function Set {
var elm;
this.elements=elm;
this.size=0;
}
Set.prototype.get = new function(index)
{
return this.elements[index];
}
Set.prototype.add = new function(object)
{
this.elements[this.size]=object;
this.size = this.size+1;
}
It turned out that GeoGebra does not recognize Sets so I tried to make a Set function.
Basically it collects all lines into a set, calculates the angles between them, groups them and makes checkboxes to trigger visuals.
the GeoGebra functions can be called via ggbApplet and the original Workspace commands via ggbApplet.evalCommand(String) and the Workspace commands I used are the basic Checkbox, SetValue and Angle commands.
The syntax for GeoGebra commands are:
Checkbox[ <Caption>, <List> ]
SetValue[ <Boolean|Checkbox>, <0|1> ]
Angle[ <Line>, <Line> ]
Thank you for your help!
In short, the syntax error you're running to is because of these lines of code:
function Set {
and after fixing this, new function(index) / new function(object) will also cause problems.
This isn't valid JS, you're likely looking for this:
function Set() {
this.elements = [];
this.size = 0;
}
Set.prototype.get = function(index) {
return this.elements[index];
};
Set.prototype.add = function(object) {
this.elements[this.size] = object;
this.size = this.size + 1;
};
Notice no new before each function as well.
I'm not sure what you're trying to accomplish by creating this Set object though - it looks like a wrapper for holding an array and its size, similar to how something might be implemented in C. In JavaScript, arrays can be mutated freely without worrying about memory.
Here's an untested refactor that removes the use of Set in favour of native JavaScript capabilities (mostly mutable arrays):
var names = ggbApplet.getAllObjectNames();
var lines = [];
var angles = [];
var groups = [];
for (var i = 0; i < names.length; i++) {
if (getObjectType(names[i].e) === "line") {
lines.push(names[i]);
}
}
for (var i = 0; i < lines.length; i++) {
for (var j = 0; j < i; j++) {
angles.push(new Angle(i, j));
}
}
for (var i = 0; i < angles.length; i++) {
var thisVal = angles[i].value;
var placed = false;
for (var j = 0; j < groups.length; j++) {
if (groups[j][0].value === thisVal) {
groups[j].push(angles[i]);
placed = true;
}
}
if (!placed) {
groups.push([angles[i]]);
}
}
for (var i = 0; i < groups.length; i++) {
var list = "";
for (var j = 0; j < groups[i].length; j++) {
list += groups[i][j].name;
if (j != groups[i].length - 1) {
list += ",";
}
}
var comm1 = "Checkbox[angle_{" + groups[i][0].value + "},{" + list + "}]";
ggbApplet.evalCommand(comm1);
var comm2 = "SetValue[angle_{" + groups[i][0].value + "}+,0]";
ggbApplet.evalCommand(comm2);
}
function Angle(i, j) {
this.name = "angleA_" + i + "B_" + j;
var comm3 = "angleA_" + i + "B_" + j + " = Angle[" + lines[i] + "," + lines[j] + "]";
ggbApplet.evalCommand(comm3);
var val = ggbApplet.getValue(this.name);
if (val > 180) {
val -= 180;
}
this.value = val;
ggbApplet.setVisible(name, false);
}
Hopefully this helps!
Your function definition is missing the parameter list after the function name.
Also, you're initializing the elements property to an undefined value. You need to initialize it to an empty array, so that the add method can set elements of it.
function Set() {
this.elements=[];
this.size=0;
}

Javascript array to point variable name with similar function

I'm want to shorten this function with array
document.mySchedule.breakfast.onchange = function() {
var id = document.mySchedule.breakfast.selectedIndex;
var val = document.mySchedule.breakfast[id].value;
strUser[0]=val;
}
document.mySchedule.lunch.onchange = function() {
var id = document.mySchedule.lunch.selectedIndex;
var val = document.mySchedule.lunch[id].value;
strUser[1]=val;
}
document.mySchedule.dinner.onchange = function() {
var id = document.mySchedule.dinner.selectedIndex;
var val = document.mySchedule.dinner[id].value;
strUser[2]=val;
}
I'm try this way but it didn't seem to be work.
var selectData = ["breakfast","lunch","dinner"]
for(i = 0; i < selectData.lenght; i++) {
document.mySchedule.selectData[i].onchange = function() {
var id = document.mySchedule.selectData[i].selectedIndex;
var val = document.mySchedule.selectData[i][id].value;
strUser[i]=val;
}
}
by the way this use to control selector.
Hope someone can help. thank you
Use:
var selectData = ["breakfast","lunch","dinner"]
for(i = 0; i < selectData.lenght; i++) {
var e = document.getElementById(selectData[i]);
e.onchange = function(){
strUser[i] = e.value;
};
}

Categories