How to add one more property to the dynamically created array? - javascript

var props = [
"current_day", "open_val", "high_val", "low_val", "close_val"
];
var data = [
{
"current_day":"2011-08-01",
"open_val":136.65,
"high_val":136.96,
"low_val":134.15,
"close_val":134.15
},
{
"current_day":"2011-08-02",
"open_val":135.26,
"high_val":135.95,
"low_val":131.50,
"close_val":131.85
}
]
var arrays = [];
for ( var i = 0; i < data.length; ++i )
{
var array = [];
for ( var j = 0; j < props.length; ++j )
{
array.push( data[i][props[j]] );
}
arrays.push(array);
}
console.log(JSON.stringify(arrays));
When i run the output of this is
[["2011-08-01",136.65,136.96,134.15,134.15],["2011-08-02",135.26,135.95,131.5,131.85]]
Could you please tell me how can i add close_value also at the end of the array so that it looks like this
[["2011-08-01",136.65,136.96,134.15,134.15,134.15],["2011-08-02",135.26,135.95,131.5,131.85,131.85]]
http://jsfiddle.net/4pxrhhvj/

Just like this? Updated your fiddle JSFiddle
var nprops = [
"close_val"
];
for ( var i = 0; i < data.length; ++i )
{
for ( var ii = 0; ii < arrays.length; ++ii )
{
for ( var j = 0; j < nprops.length; ++j )
{
var closeval = '';
closeval = data[i][nprops[j]] ;
}
arrays[ii].push(closeval);
}
}
for ( var i1 = 0; i1 < arrays.length; ++ii )
{
arrays[i1].pop();
}
console.log(JSON.stringify(arrays));

You can use if/else in the inner for loop:
var props = [
"current_day", "open_val", "high_val", "low_val", "close_val"
];
var data = [{
"current_day": "2011-08-01",
"open_val": 136.65,
"high_val": 136.96,
"low_val": 134.15,
"close_val": 134.15
}, {
"current_day": "2011-08-02",
"open_val": 135.26,
"high_val": 135.95,
"low_val": 131.50,
"close_val": 131.85
}]
var arrays = [];
for (var i = 0; i < data.length; ++i) {
var array = [];
for (var j = 0; j < props.length; ++j) {
if (props[j] !== "close_val") {
array.push(data[i][props[j]]);
} else {
array.push(data[i][props[j]]);
array.push(data[i][props[j]]);
}
}
arrays.push(array);
}
document.querySelector('pre').innerHTML = JSON.stringify(arrays);
<pre></pre>

Try this code
var props = [
"current_day", "open_val", "high_val", "low_val", "close_val"
];
var data = [{
"current_day": "2011-08-01",
"open_val": 136.65,
"high_val": 136.96,
"low_val": 134.15,
"close_val": 134.15
}, {
"current_day": "2011-08-02",
"open_val": 135.26,
"high_val": 135.95,
"low_val": 131.50,
"close_val": 131.85
}];
var arrays = [];
for (var i = 0; i < data.length; ++i) {
var array = [];
for (var j = 0; j < props.length; ++j) {
array[j] = data[i][props[j]];
}
arrays.push(array);
}
console.log(JSON.stringify(arrays));

Related

how to do multiple loops in Javascript and display data as shown in the picture

how to do multiple loops and display data as shown in the picture
I have data in the form of an array and I want to loop it so that it looks like this picture
enter image description here
here's my script
var pf_lookup = {};
var pf_item_name = [];
var pf_item_code = [];
var pf_lot = [];
var pf_pdo_item = [];
var pf_item_process = [];
for (var itemdtl, i = 0; itemdtl = data[i++];) {
//console.log(itemdtl);
var item_name = itemdtl.ITEM_NAME;
var item_code = itemdtl.ITEM_CODE;
var greige_num = itemdtl.GREIGE_NUM;
var lot = itemdtl.LOT;
var item_process = itemdtl.ITEM_PROCESS;
if (!(item_code in pf_lookup)) {
pf_lookup[item_code] = 100;
pf_item_name.push(item_name);
pf_item_code.push(item_code);
pf_greige_num.push(greige_num);
pf_lot.push(lot);
pf_item_process.push(item_process);
}
}
$.each(pf_item_code, function (i, val) {
var itemQtyPack = 0;
var WeightPack = 0;
var WeightPackLot = '';
for (var j = 0; j < data.length; ++j) {
var pf_lookupx = {};
var pf_lotxx = [];
var item_codex = data[j]['ITEM_CODE']
var lotx = (data[j]['LOT'])
var item_name = data[j]['ITEM_NAME']
var greige_num = data[j]['GREIGE_NUM']
var netto = data[j]['NETTO']
if (pf_item_code[i] == data[j]['ITEM_CODE']) {
var lotArray = lotx.split(" ")
for (var k = 0; k < lotx.length; ++k) {
}
$.each(lotArray, function (i, val) {
for (var k = 0; k < data.length; ++k) {
if (pf_item_code[i] == data[k]['ITEM_CODE']) {
}
}
})
}
}
})
I've managed to get the item_code, but when looping lots it only shows 1 lot there should be 2 lots,
and after the lot is found then looping to get the list greige_num,
how ?
The second last loop condition, shouldn't it be
for (var k = 0; k < lotArray.length; ++k) { // code ...}

Toggling JS button back and forth

my toggle button in javascript seems to work fine in turning on lightmode from default darkmode by running a function that changes the CSS. However, when I flip the button again, it does not change. This is somewhat expected since there's no reason it would change. How would I go about switching it back?
Button HTML:
<label for="ID_HERE" class="toggle-switchy" >
<input checked type="checkbox" id="ID_HERE">
<span class="toggle" onclick="lightmode();"></span>
<span class="switch"></span>
</span>
</label>
JS for button:
function lightmode() {
const bodyChanges = document.querySelectorAll('.margin_body');
for (let i = 0; i < bodyChanges.length; i++) {
bodyChanges[i].style.background = 'white';
}
/*const bodyChanges = document.querySelectorAll('.margin_body');
for (let i = 0; i < bodyChanges.length; i++) {
bodyChanges[i].style.backgroundImage = '';
} */
const paraChanges = document.querySelectorAll('.paragraph');
for (let i = 0; i < paraChanges.length; i++) {
paraChanges[i].style.color = 'black';
}
const topTitleChanges = document.querySelectorAll('.toptitle');
for (let i = 0; i < topTitleChanges.length; i++) {
topTitleChanges[i].style.color = 'black';
}
const alphabetSChanges = document.querySelectorAll('.AlphabetS');
for (let i = 0; i < alphabetSChanges.length; i++) {
alphabetSChanges[i].style.color = 'black';
}
const arowanaContainerChanges = document.querySelectorAll('.arowanacontainer');
for (let i = 0; i < arowanaContainerChanges.length; i++) {
arowanaContainerChanges[i].style.background = 'white';
}
const fishContainerChanges = document.querySelectorAll('.fishcontainer');
for (let i = 0; i < fishContainerChanges.length; i++) {
fishContainerChanges[i].style.background = 'white';
}
const articleContainerChanges = document.querySelectorAll('.articlescontainer');
for (let i = 0; i < articleContainerChanges.length; i++) {
articleContainerChanges[i].style.background = 'white';
}
const sideTextChanges = document.querySelectorAll('.sidetext');
for (let i = 0; i < sideTextChanges.length; i++) {
sideTextChanges[i].style.color = 'black';
}
const topMenuChanges = document.querySelectorAll('.topmenu');
for (let i = 0; i < topMenuChanges.length; i++) {
topMenuChanges[i].style.background = '#fff2f2';
}
const h3Changes = document.querySelectorAll('h3');
for (let i = 0; i < h3Changes.length; i++) {
h3Changes[i].style.background = '#fff2f2';
}
const articlePageChanges = document.querySelectorAll('.articlepage');
for (let i = 0; i < articlePageChanges.length; i++) {
articlePageChanges[i].style.color = 'black';
}
const articleTeaserChanges = document.querySelectorAll('.articleteaser');
for (let i = 0; i < articleTeaserChanges.length; i++) {
articleTeaserChanges[i].style.color = 'black';
}
/*const buttonTextChanges = document.querySelectorAll('.button_text');
for (let i = 0; i < buttonTextChanges.length; i++) {
buttonTextChanges[i].style.color = '#0C0C0C';*/
const box2Changes = document.querySelectorAll('.box2');
for (let i = 0; i < box2Changes.length; i++) {
box2Changes[i].style.color = 'rgb(245, 245, 245)';
}
const box3Changes = document.querySelectorAll('.box3');
for (let i = 0; i < box3Changes.length; i++) {
box3Changes[i].style.color = 'rgb(245, 245, 245)';
}
const projectPhoto1Changes = document.querySelectorAll('.projectphoto1');
for (let i = 0; i < projectPhoto1Changes.length; i++) {
projectPhoto1Changes[i].style.backgroundImage = 'linear-gradient(to bottom, #Fdfcfa 50%, lightgrey 50%)';
}
const section1Changes = document.querySelectorAll('.section1');
for (let i = 0; i < section1Changes.length; i++) {
section1Changes[i].style.backgroundColor = '#fff2f2';
}
const section1textChanges = document.querySelectorAll('.section1text');
for (let i = 0; i < section1textChanges.length; i++) {
section1textChanges[i].style.color = 'black';
}
const section1smalltextChanges = document.querySelectorAll('.section1smalltext');
for (let i = 0; i < section1smalltextChanges.length; i++) {
section1smalltextChanges[i].style.color = 'black';
}
const button_textChanges = document.querySelectorAll('.button_text');
for (let i = 0; i < button_textChanges.length; i++) {
button_textChanges[i].style.color = 'black';
}
const polygonfrontChanges = document.querySelectorAll('.polygonfront');
for (let i = 0; i < polygonfrontChanges.length; i++) {
polygonfrontChanges[i].style.fill = '#fff2f2';
}
const bgChanges = document.querySelectorAll('.bg');
for (let i = 0; i < bgChanges.length; i++) {
bgChanges[i].style.backgroundImage = 'url(".jpg")';
}
const bg2Changes = document.querySelectorAll('.bg2');
for (let i = 0; i < bg2Changes.length; i++) {
bg2Changes[i].style.backgroundImage = 'url(".jpg")';
}
const bg3Changes = document.querySelectorAll('.bg3');
for (let i = 0; i < bg3Changes.length; i++) {
bg3Changes[i].style.backgroundImage = 'url(".jpg")';
}
}
When clicking, you should check the input status to know if the mode should toggle to light or dark mode.
<span class="toggle" onclick="toggle()"></span>
function toggle() {
if(document.getElementById("ID_HERE").checked)
lightmode()
else
darkmode()
}

A* Pathfinding, path not showing up

I have this code, in script (p5.js), I am running it and works as expected, but the moment I include the path code, that helps in finding the previous parents to form a path to the end goal, the browser crushes, as the images show. It fist colors the 3 cells then crashes. Here is the code.
var col = 12, row = 12, grid = new Array(col), openSet = [], closeSet = [], start, end, w, h, path = [];
function removefromArray(array_, element){
for(var i = array_.length - 1; i >= 0; i--){
if(array_[i] == element){
array_.splice(i, 1);
}
}
}
function heuristic(a, b){
var distance = abs(a.i - b.i) + abs(a.j - b.j);
return distance;
}
function Spot(i, j){
this.i = i;
this.j = j;
this.f = 0;
this.g = 0;
this.h = 0;
this.neighbor = [];
this.parent = undefined;
this.wall = false;
this.show = function (color){
fill(color);
if(this.wall){
fill(0);
}
noStroke();
rect(this.i * w, this.j * h, w - 1, h - 1);
}
this.addNeighbor = function(grid){
var i = this.i, j = this.j;
if(i < col - 1){
this.neighbor.push(grid[i+1] [j]);
}
if(i > 0){
this.neighbor.push(grid[i-1] [j]);
}
if(j < row-1){
this.neighbor.push(grid[i] [j+1]);
}
if(j > 0){
this.neighbor.push(grid[i] [j-1]);
}
}
}
function setup(){
createCanvas(500,500);
console.log("A*");
w = width / col;
h = height / row;
for( var i = 0; i< col; i++){
grid[i] = new Array(row);
}
//Adding a spot
for( var i = 0; i< col; i++){
for( var j = 0; j< row; j++){
grid[i][j] = new Spot(i,j);
}
}
//Adding a neighbor
for( var i = 0; i< col; i++){
for( var j = 0; j< row; j++){
grid[i][j].addNeighbor(grid);
}
}
start = grid[0][0];
end = grid[col - 1][row - 1];
openSet.push(start);
}
function draw(){
var winner = 0;
if(openSet.length > 0){
for( var i = 0; i< openSet.length; i++){
if(openSet[i].f < openSet[winner].f){
winner = i;
}
}
var current = openSet[winner];
if(current === end){
noLoop();
console.log("Done!");
}
removefromArray(openSet, current);
closeSet.push(current);
var neighbors = current.neighbor;
for(var i = 0; i < neighbors.length; i++){
var the_neighbor = neighbors[i];
if(!closeSet.includes(the_neighbor)){
var tempG = current.g + 1;
}
if(openSet.includes(the_neighbor)){
if(tempG < the_neighbor.g){
the_neighbor.g = tempG;
}
}
else{
the_neighbor.g = tempG;
openSet.push(the_neighbor);
}
the_neighbor.h = heuristic(the_neighbor, end);
the_neighbor.f = the_neighbor.g + the_neighbor.h;
the_neighbor.parent = current; // the previous node
}
}
else{
// no solution
}
background(0)
for( var i = 0; i< col; i++){
for( var j = 0; j< row; j++){
grid[i][j].show(color(255));
}
}
for( var i = 0; i< openSet.length; i++){
openSet[i].show(color("green"));
}
for( var i = 0; i< closeSet.length; i++){
closeSet[i].show(color("red"));
}
// path = [];
// var temp = current;
// path.push(temp);
// while(temp.parent){
// path.push(temp.parent);
// temp = temp.parent;
// }
// for(var i = 0; i < path.length; i++){
// path[i].show(color(0,0,255));
// }
}
If I try to remove the comments slash for this last part, the system will run for about 5secs then crashes. Someone with the solution, I will highly appreciate.
Result when the path part is uncommented
You are generating a cycle somehow in the chain of parents (i.e. Spot A has parent Spot B and Spot B has parent Spot A), which is causing an infinite loop. I'm not sure exactly where/why this is happening. Your code is a bit hard to read. You should avoid nondescript one letter variable & property names.
Also there are several scoping issues that may be causing unexpected behavior. The keyword var is the worst element of any programming language since goto and it should be scoured from the face of the internet with the fire of 1000 suns. Please use let. See the comments below for more explanation.
var col = 12,
row = 12,
grid = new Array(col),
openSet = [],
closeSet = [],
start, end, w, h, path = [];
function removefromArray(array_, element) {
for (let i = array_.length - 1; i >= 0; i--) {
if (array_[i] == element) {
array_.splice(i, 1);
}
}
}
function heuristic(a, b) {
var distance = abs(a.i - b.i) + abs(a.j - b.j);
return distance;
}
function Spot(i, j) {
this.i = i;
this.j = j;
this.f = 0;
this.g = 0;
this.h = 0;
this.neighbor = [];
this.parent = undefined;
this.wall = false;
this.show = function(color) {
fill(color);
if (this.wall) {
fill(0);
}
noStroke();
rect(this.i * w, this.j * h, w - 1, h - 1);
}
this.addNeighbor = function(grid) {
let i = this.i,
j = this.j;
if (i < col - 1) {
this.neighbor.push(grid[i + 1][j]);
}
if (i > 0) {
this.neighbor.push(grid[i - 1][j]);
}
if (j < row - 1) {
this.neighbor.push(grid[i][j + 1]);
}
if (j > 0) {
this.neighbor.push(grid[i][j - 1]);
}
}
}
function setup() {
createCanvas(500, 500);
console.log("A*");
w = width / col;
h = height / row;
for (let i = 0; i < col; i++) {
grid[i] = new Array(row);
}
//Adding a spot
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
grid[i][j] = new Spot(i, j);
}
}
//Adding a neighbor
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
grid[i][j].addNeighbor(grid);
}
}
start = grid[0][0];
end = grid[col - 1][row - 1];
openSet.push(start);
}
function draw() {
let winner = 0;
let current
if (openSet.length > 0) {
for (let i = 0; i < openSet.length; i++) {
if (openSet[i].f < openSet[winner].f) {
winner = i;
}
}
current = openSet[winner];
if (current === end) {
noLoop();
console.log("Done!");
}
removefromArray(openSet, current);
closeSet.push(current);
var neighbors = current.neighbor;
for (let i = 0; i < neighbors.length; i++) {
var the_neighbor = neighbors[i];
// The use of var here results in very weird behavior
// where tempG's value is preserved from the previous
// iteration of this loop even when it is not assigned
// a value. If that is desired you should declare this
// variable outside of the for loop.
//
// If you always use let isntead of var you will get
// errors instead of bizarre behavior. That will help
// you be deliberate about your variable scoping.
if (!closeSet.includes(the_neighbor)) {
var tempG = current.g + 1;
} else {
print('tempG not set');
}
if (openSet.includes(the_neighbor)) {
if (tempG < the_neighbor.g) {
the_neighbor.g = tempG;
}
} else {
print(`tempG: ${tempG}`);
the_neighbor.g = tempG;
openSet.push(the_neighbor);
print(`openSet: ${openSet.length}`);
}
the_neighbor.h = heuristic(the_neighbor, end);
the_neighbor.f = the_neighbor.g + the_neighbor.h;
the_neighbor.parent = current; // the previous node
}
} else {
// no solution
}
background(0)
for (let i = 0; i < col; i++) {
for (var j = 0; j < row; j++) {
grid[i][j].show(color(255));
}
}
for (let i = 0; i < openSet.length; i++) {
openSet[i].show(color("green"));
}
for (let i = 0; i < closeSet.length; i++) {
closeSet[i].show(color("red"));
}
path = [];
let temp = current;
path.push(temp);
while (temp.parent) {
if (path.includes(temp.parent)) {
print('Cycle detected!');
console.log({ current: { i: temp.i, j: temp.j }, parent: { i: temp.parent.i, j: temp.parent.j } });
break;
}
path.push(temp.parent);
temp = temp.parent;
}
for (let i = 0; i < path.length; i++) {
path[i].show(color(0, 0, 255));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.js"></script>
Update: Infinite Loop Fix
The part of your code that updates neighbors deviates from the definition of A* pretty substantially. Here's what I came up with (single letter variable names replaces with meaningful names):
let tentativePathScore = current.shortestPathScore + 1;
if (the_neighbor.heuristicScore === undefined) {
the_neighbor.heuristicScore = heuristic(the_neighbor, end);
}
if (the_neighbor.combinedScore === undefined ||
tentativePathScore + the_neighbor.heuristicScore < the_neighbor.combinedScore) {
// Update the path score and combined score for this neighbor.
the_neighbor.shortestPathScore = tentativePathScore;
the_neighbor.combinedScore = the_neighbor.shortestPathScore + the_neighbor.heuristicScore;
the_neighbor.parent = current; // the previous node
if (!openSet.includes(the_neighbor)) {
openSet.push(the_neighbor);
}
}
And here's a working snippet with walls added:
let col = 12,
row = 12,
grid = new Array(col),
openSet = [],
closeSet = [],
start, end, w, h, path = [];
function removefromArray(array_, element) {
for (let i = array_.length - 1; i >= 0; i--) {
if (array_[i] == element) {
array_.splice(i, 1);
}
}
}
function heuristic(a, b) {
if (a.wall) {
return Infinity;
}
return abs(a.i - b.i) + abs(a.j - b.j);
}
function Spot(i, j) {
this.i = i;
this.j = j;
this.combinedScore = undefined;
this.shortestPathScore = undefined;
this.heuristicScore = undefined;
this.neighbor = [];
this.parent = undefined;
this.wall = false;
this.show = function(color) {
fill(color);
if (this.wall) {
fill(0);
}
noStroke();
rect(this.i * w, this.j * h, w - 1, h - 1);
}
this.addNeighbor = function(grid) {
let i = this.i,
j = this.j;
if (i < col - 1) {
this.neighbor.push(grid[i + 1][j]);
}
if (i > 0) {
this.neighbor.push(grid[i - 1][j]);
}
if (j < row - 1) {
this.neighbor.push(grid[i][j + 1]);
}
if (j > 0) {
this.neighbor.push(grid[i][j - 1]);
}
}
}
function setup() {
createCanvas(500, 500);
console.log("A*");
w = width / col;
h = height / row;
for (let i = 0; i < col; i++) {
grid[i] = new Array(row);
}
//Adding a spot
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
grid[i][j] = new Spot(i, j);
}
}
//Adding a neighbor
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
grid[i][j].addNeighbor(grid);
}
}
// make walls
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
if ((i > 1 || j > 1) && (i < col - 2 || j < row - 2) && random() < 0.2) {
grid[i][j].wall = true;
}
}
}
start = grid[0][0];
end = grid[col - 1][row - 1];
start.shortestPathScore = 0;
start.heuristicScore = heuristic(start, end);
start.combinedScore = start.shortestPathScore + start.heuristicScore;
openSet.push(start);
}
function draw() {
let winner = 0;
let current;
if (openSet.length > 0) {
for (let i = 0; i < openSet.length; i++) {
if (openSet[i].combinedScore < openSet[winner].combinedScore) {
winner = i;
}
}
current = openSet[winner];
if (current === end) {
noLoop();
console.log("Done!");
}
removefromArray(openSet, current);
closeSet.push(current);
var neighbors = current.neighbor;
for (let i = 0; i < neighbors.length; i++) {
var the_neighbor = neighbors[i];
let tentativePathScore = current.shortestPathScore + 1;
if (the_neighbor.heuristicScore === undefined) {
the_neighbor.heuristicScore = heuristic(the_neighbor, end);
}
if (the_neighbor.combinedScore === undefined ||
tentativePathScore + the_neighbor.heuristicScore < the_neighbor.combinedScore) {
// Update the path score and combined score for this neighbor.
the_neighbor.shortestPathScore = tentativePathScore;
the_neighbor.combinedScore = the_neighbor.shortestPathScore + the_neighbor.heuristicScore;
the_neighbor.parent = current; // the previous node
if (!openSet.includes(the_neighbor)) {
openSet.push(the_neighbor);
}
}
}
} else {
// no solution
}
background(0)
for (let i = 0; i < col; i++) {
for (let j = 0; j < row; j++) {
grid[i][j].show(color(255));
}
}
for (let i = 0; i < openSet.length; i++) {
openSet[i].show(color("green"));
}
for (let i = 0; i < closeSet.length; i++) {
closeSet[i].show(color("red"));
}
path = [];
let temp = current;
path.push(temp);
while (temp.parent) {
if (path.includes(temp.parent)) {
print('Cycle detected!');
break;
}
path.push(temp.parent);
temp = temp.parent;
}
for (let i = 0; i < path.length; i++) {
path[i].show(color(0, 0, 255));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.js"></script>

Hierarchical Clustering in JavaScript

I have some markers on google maps and I would like to identify clusters by point-to-point distance between them. However, I am having a bit of difficulty:
First I loop through all the markers and create an array which is:
for (var i = 0; i < MARKERS.length - 1; i++) {
for (var j = i + 1; j < MARKERS.length; j++) {
var distance_between = google.maps.geometry.spherical.computeDistanceBetween(point_i, point_j)
var valueToPush = {}
valueToPush.fromMarker = name_i
valueToPush.toMarker = name_j
valueToPush.distance = distance_between
cluster_array.push(valueToPush)
}
}
What I would then like to do is run a hierarchical clustering algorithm like this:
var cluster = .cluster(cluster_array, MAX, threshold)
Where if I specify 500 for threshold then I get a list like this
Cluster 0: Marker A, Marker Y, Marker C
Cluster 1: Marker B
Cluster 2: Marker D, Marker E
etc.
Where each cluster shows me the markers that are within 500 metres of each other.
Thanks very much
If it helps this is what I ended up doing:
function the_clusterer(cluster_array, num_radius) {
console.log('Clustering distance array')
for (var i = 0; i < cluster_array.length - 1; i++) {
if (typeof(cluster_array[i]) != 'undefined') {
var size_outer = 0,
key_outer;
for (key_outer in cluster_array[i]) {
if (cluster_array[i].hasOwnProperty(key_outer));
size_outer++;
}
for (var j = 0; j < size_outer; j++) {
for (var k = i + 1; k < cluster_array.length; k++) {
if (typeof(cluster_array[i]) != 'undefined') {
var size_inner = 0,
key_inner;
for (key_inner in cluster_array[k]) {
if (cluster_array[k].hasOwnProperty(key_inner));
size_inner++;
}
var found_outer = 0
for (var l = 0; l < size_inner; l++) {
if (found_outer === 1) {
break;
}
if (cluster_array[k][l] == cluster_array[i][j]) {
found_outer++
}
}
if (found_outer > 0) {
for (var l = 0; l < size_inner; l++) {
var found_inner = 0
for (var m = 0; m < size_outer; m++) {
if (cluster_array[i][m] == cluster_array[k][l]) {
found_inner++
}
}
if (found_inner == 0) {
cluster_array[i][size_outer] = cluster_array[k][l]
size_outer++
}
}
delete cluster_array[k];
}
}
}
}
}
}
txtOutput.value += "Start Clusters: " + num_radius + "m.\n"
var k = 0
for (var i = 0; i < cluster_array.length - 1; i++) {
var size_outer = 0,
key_outer;
for (key_outer in cluster_array[i]) {
if (cluster_array[i].hasOwnProperty(key_outer));
size_outer++;
}
if (size_outer > 0) {
k++
var temp_line = "Cluster " + k + ":"
for (var j = 0; j < size_outer; j++) {
temp_line = temp_line + " Marker " + cluster_array[i][j]
}
txtOutput.value += temp_line + ".\n"
}
}
}

JavaScript Json row undefined for TreeView

I have a question. When querying my Json object, although i have my Field as same name and all Json rows available give me an error that is undefined.
//e.g: row.DepParentId
Bellow is my code. Am I missing some tag?
function convert(rows) {
debugger;
function exists(rows, parent) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].DepId === parent) return true;
}
return false;
}
var nodes = [];
// get the top level nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!exists(rows, row.DepParentId)) {
nodes.push({
id: row.DepId,
name: row.Title
});
}
}
var toDo = [];
for (var i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
var node = toDo.shift();
// the parent node
// get the children nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.DepParentId == node.Id) {
var child = {
Id: row.DepId,
Name: row.Title
};
if (node.options) {
node.options.push(child);
} else {
node.options = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
My Json example for one row picked from Firefox
"{"DepId":7,"DepParentId":3,"Title":"OTT"}"
Thanks for helping
Joao
thanks all for helping, it's working now, the problem was the JSON.stringify() was returning only an [Object] so when you use JSON.parse() generates a sintax error.
function onLoaded() {
var itemsCount = items.get_count();
for (var i = 0; i < itemsCount; i++) {
var item = items.itemAt(i);
var dep = JSON.stringify(item.get_fieldValues());
deps.push(dep);
}
So, i had to change the format to be valid to parse like this
var dt = "[" + deps + "]";
var ret = JSON.parse(dt);
Thanks
Joao

Categories

Resources