Not getting the expected results from for loop [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm having trouble with a if statement in a for loop where the items are not fitting under the h1 like i would of expected it's almost like the if is been missed the first go and that messes things up
Here is some example code and the jsfiddle to go with it http://jsfiddle.net/xpvt214o/714036/
var jsonOut = [{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
]
var content = ''
var lastDate = 0
for (var i = 0; i < jsonOut.length; i++) {
var testDate = new Date(jsonOut[i].timestamp * 1000);
var contentNow = ''
var ResultName = ''
var h1marker = ''
for (var j = 0; j < jsonOut[i].check.length; j++) {
ResultName = ResultName + '' + jsonOut[i].check[j].name + '<br>'
contentNow = testDate + '<br>' + ResultName
}
if (jsonOut[i].timestamp != lastDate) {
h1marker = "<h1>" + testDate.getDate() + "</h1>"
lastDate = jsonOut[i].timestamp
}
content = h1marker + contentNow + content
}
$("#tests").html(content)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tests">
</div>

There is no problem with your if-statement at all. Your code at this part
content = h1marker + contentNow + content
Puts the new content IN FRONT of the old, therefore your second entry for each date is above the header "30".
Change it to content = content + h1marker + contentNow like in the following snippet:
var jsonOut = [{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535678338,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
{
"check": [{
"name": "Singapore",
},
{
"name": "SanFrancisco",
},
{
"name": "Sydney",
}
],
"timestamp": 1535594440,
},
]
var content = ''
var lastDate = 0
for (var i = 0; i < jsonOut.length; i++) {
var testDate = new Date(jsonOut[i].timestamp * 1000);
var contentNow = ''
var ResultName = ''
var h1marker = ''
for (var j = 0; j < jsonOut[i].check.length; j++) {
ResultName = ResultName + '' + jsonOut[i].check[j].name + '<br>'
contentNow = testDate + '<br>' + ResultName
}
if (jsonOut[i].timestamp != lastDate) {
h1marker = "<h1>" + testDate.getDate() + "</h1>"
lastDate = jsonOut[i].timestamp
}
content = content + h1marker + contentNow
}
$("#tests").html(content)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tests">
</div>

Related

How to delete a row from json while getting a json using javascript

I am trying to get a json .Which row has a null value I want to delete it using javascript.
Suppose my json is like
[{
"unit_id": "9",
"CHGRAPHUpdatetime": {
"time": "2018-03-15 00:00:00"
},
"channelGraph": [{
"chkey": "ch1",
"list": "1"
}, {
"chkey": null,
"list": null
}]
}]
If chkey and chvalue is null then row will be deleted.
Expected result is
[{
"unit_id": "9",
"CHGRAPHUpdatetime": {
"time": "2018-03-15 00:00:00"
},
"channelGraph": [{
"chkey": "ch1",
"list": "1"
}]
}]
Could you please help me to resolve this problem.
Assuming you've serialised your JSON into a JavaScript object:
var my_array = [{
"unit_id": "9",
"CHGRAPHUpdatetime": {
"time": "2018-03-15 00:00:00"
},
"channelGraph": [{
"chkey": "ch1",
"list": "1"
}, {
"chkey": null,
"list": null
}]
}];
document.write("<pre>" + JSON.stringify(my_array) + "</pre>");
for (var i = 0; i < my_array.length; i += 1) {
var rows = my_array[i].channelGraph;
for (var j = 0; j < rows.length; j += 1) {
if (rows[j].chkey === null && rows[j].chkey === null) {
rows.splice(j, 1); // Removes one row at index j
j -= 1; // Avoid skipping a row -
// we want the next row to be next.
}
}
}
document.write("<pre>" + JSON.stringify(my_array) + "</pre>");
Try this :
var obj = [{
"unit_id": "9",
"CHGRAPHUpdatetime": {
"time": "2018-03-15 00:00:00"
},
"channelGraph": [{
"chkey": "ch1",
"list": "1"
}, {
"chkey": null,
"list": null
}]
}];
obj[0].channelGraph.filter((item, index) => {
(!item.chkey && !item.list) ? obj[0].channelGraph.splice(index, 1) : '';
});
console.log(obj);

Jquery multiply input number value and Json data

I have a time calculation tool which you can find in the following fiddle link. Once someone has selected a platform, task type, component and number of units, the number of units entered should be multiplied with selected component value and show it on the below table. I have managed to get the all populated values but can't do the math. I have tried several attempts but it wasn't working.
var myJson = {
"platforms": [
{
"name": "Sitecore",
"id": "sitecore",
"tasktype": [
{
"name": "Promobox",
"id": "promobox",
"components": [
{
"name": "Accordion",
"id": "accordion",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "video",
"components": [
{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "siab",
"tasktype": [
{
"name": "Newswire",
"id": "newswire",
"components": [
{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "tasktypenew",
"components": [
{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function (index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function () {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function (index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function () {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function (index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function () {
$('#calculate').click(function () {
$('#calc input, #calc select').each(
function (index) {
var input = $(this);
$('#data tbody').append('<tr><td>' + input.val() + '</td></tr>');
});
});
});
JS Fiddle
Ok this took a lot of debugging. You were building your table wrong and not storing data properly. The whole fishing for data was problematic. Here is the debugged calculator:
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
console.log(tr);
$('#calc input, #calc select').each( function (index) {
console.log($(this));
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + input.val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
});
});
notice:
Change of table structure format.
Now appending td's to single tr each time in order to sustain table-row consistency.
Fishing data from row with the help of adding class tag identifier to each td
Showing result.
update fiddle link:
https://jsfiddle.net/x4rLuf88/1/

How to not repeat folders with JStree?

I have a JSON file with some data like this:
dataTree.json =
[
{
"datap": "816816816816816818",
"name": "image1.jpg",
"url": "/files/folder1/test/d2e9c54ceedc9/image1.jpg",
"path": "/files/folder1/test/image1.jpg",
"size": 35969
},
{
"datap": "857022de4fccdcb54623ff6185daae706a47140c",
"name": "image2.jpg",
"url": "/files/folder1/pruebas/85623ff6185d7140c/image2.jpg",
"path": "/files/folder1/pruebas/image2.jpg",
"size": 17689282
},
{
"datap": "b260ec3250420c953a9db41897c34e3551620ec325035516256b2/image3.jpg",
"path": "/files/folder1/test/image3.jpg",
"size": 710632
}
]
In this part I make the operation and the format for jstree
$.getJSON('/dataTree.json', function (response) {
var fullTree = [];
if (response == []){
var refullTree = []
}
else {
var refullTree = [{"id":null,"text":"Root","icon":"tree.png","state":null,"children":[]}]
}
function treeElements(element, tree){
var parts = element.path.split("/");
parts.splice(0,2);
for (var k in parts) {
var count = 0
var part = parts[k];
if (part == "") part = "#";
var item = {"id":null, "text": part, "icon": icon(part), "children": []};
tree.push(item);
tree = item.children;
}
function icon(search){
if (search.indexOf(".png",".jpg") > -1){
return "glyphicon glyphicon-picture" }
else if(search.indexOf("jpg",".jpg") > -1){
return "glyphicon glyphicon-picture" }
}
}
for (var i in response) {
treeElements(response[i], fullTree);
}
refullTree[0]["children"] = fullTree
});
The result is output in this format:
[
{
"id": null,
"text": "Root",
"icon": "tree.png",
"state": null,
"children": [
{
"id": null,
"text": "folder1",
"children": [
{
"id": null,
"text": "test",
"children": [
{
"id": null,
"text": "image1.jpg",
"icon": "glyphicon glyphicon-picture",
"children": []
}
]
}
]
},
{
"id": null,
"text": "folder1",
"children": [
{
"id": null,
"text": "pruebas",
"children": [
{
"id": null,
"text": "image2.jpg",
"icon": "glyphicon glyphicon-picture",
"children": []
}
]
}
]
},
{
"id": null,
"text": "folder1",
"children": [
{
"id": null,
"text": "test",
"children": [
{
"id": null,
"text": "image3.jpg",
"icon": "glyphicon glyphicon-picture",
"children": []
}
]
}
]
}
]
}
]
This tree was produced by jstree, and the three folders have the same name. I do not want to create three folders with the same name, I want that when I find a folder that exists, the data is entered into the that existing folder.
Instead, I want this:
Here is a demo of how to parse this structure: http://jsfiddle.net/DGAF4/506/
Here is the actual parsing code (also visible in the fiddle);
var tmp = {}, i, j, k, l, p1, p2, fin = [];
for(i = 0, j = a.length; i < j; i++) {
p1 = a[i].path.replace(/^\//,'').split('/');
p2 = '';
for(k = 0, l = p1.length; k < l; k++) {
tmp[p2 + '/' + p1[k]] = {
id : p2 + '/' + p1[k],
parent : p2 ? p2 : '#',
text : p1[k]
};
p2 += '/' + p1[k];
}
for(k in a[i]) {
if(a[i].hasOwnProperty(k)) {
tmp[a[i].path][k] = a[i][k];
}
}
if(a[i].path.match(/(jpg|png|jpeg)$/)) {
tmp[a[i].path].icon = "glyphicon glyphicon-picture";
}
}
for(i in tmp) {
if(tmp.hasOwnProperty(i)) {
fin.push(tmp[i]);
}
}
// fin contains the structure in a jstree compatible format

String not being appended in function

I am trying to parse a JSON and build a HTML string to append to the DOM but no matter what I do the string is only returning the first element in the JSON.
Here's the js:
var menu_json = {
"name": "Personal Banking",
"url": "/test1.html",
"children": [
{
"id": "1",
"name": "test2",
"url": "/products/deposits/test2.html",
"children": [
{
"id": "1",
"name": "test3",
"url": "/products/deposits/test3.html",
"children": [
{
"id": "1",
"name": "test5",
"url": "test5"
},
{
"id": "2",
"name": "test6",
"url": "/products/deposits/test6.html"
},
{
"id": "3",
"name": "test7",
"url": "/products/deposits/test7.html"
},
{
"id": "4",
"name": "test8",
"url": "/products/deposits/test8.html"
},
{
"id": "5",
"name": "test9",
"url": "/products/deposits/test9.html"
},
{
"id": "6",
"name": "test10",
"url": "/products/deposits/test10.html"
},
{
"id": "7",
"name": "test11",
"url": "/products/deposits/test11.html"
}
]
}
]
}
]
}
var test_html = "<ul>",
buildNavHelper = function(curNode){
test_html += "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper) + "</ul>";
}
test_html += "</li>";
};
buildNavHelper(menu_json);
test_html += "</ul>";
$('#thing').append(test_html);
Heres a fiddle
https://jsfiddle.net/w734bvw7/
buildNavHelper() has no return statement, so there's nothing coming back from _.map(). The outer test_html isn't in scope. Try this:
buildNavHelper = function(curNode){
var test_html = "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper).join("") + "</ul>";
}
test_html += "</li>";
return test_html;
};
test_html = "<ul>" + buildNavHelper(menu_json) + "</ul>";
Note the addition of .join() to avoid having commas in your output.
Also, there's no need to use underscore here; Array.map() is native Javascript.
buildNavHelper = function(curNode){
var test_html = "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + curNode.children.map(buildNavHelper).join("") + "</ul>";
}
test_html += "</li>";
return test_html;
};
https://jsfiddle.net/w734bvw7/3/
buildNavHelper = function(curNode){
var test_html = "<ul>";
test_html += "<li>" + curNode.name;
if (curNode.hasOwnProperty('children')){
test_html += "<ul>" + _.map(curNode.children, buildNavHelper) + "</ul>";
}
test_html += "</li>";
test_html += "</ul>";
return test_html;
};
$('#thing').append(buildNavHelper(menu_json));
Building the list using HTML strings can produce HTML injection. I recommend DOM methods instead:
function buildNavHelper(arr) {
var ul = document.createElement('ul');
for(var i=0; i<arr.length; ++i) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(arr[i].name));
if(arr[i].children)
li.appendChild(buildNavHelper(arr[i].children));
ul.appendChild(li);
}
return ul;
}
var menu_json = {
"name": "Personal Banking",
"url": "/test1.html",
"children": [
{
"id": "1",
"name": "test2",
"url": "/products/deposits/test2.html",
"children": [
{
"id": "1",
"name": "test3",
"url": "/products/deposits/test3.html",
"children": [
{
"id": "1",
"name": "test5",
"url": "test5"
},
{
"id": "2",
"name": "test6",
"url": "/products/deposits/test6.html"
},
{
"id": "3",
"name": "test7",
"url": "/products/deposits/test7.html"
},
{
"id": "4",
"name": "test8",
"url": "/products/deposits/test8.html"
},
{
"id": "5",
"name": "test9",
"url": "/products/deposits/test9.html"
},
{
"id": "6",
"name": "test10",
"url": "/products/deposits/test10.html"
},
{
"id": "7",
"name": "test11",
"url": "/products/deposits/test11.html"
}
]
}
]
}
]
}
function buildNavHelper(arr) {
var ul = document.createElement('ul');
for(var i=0; i<arr.length; ++i) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(arr[i].name));
if(arr[i].children)
li.appendChild(buildNavHelper(arr[i].children));
ul.appendChild(li);
}
return ul;
}
document.querySelector('#thing').appendChild(buildNavHelper([menu_json]));
<div id="thing"></div>

How to look for a particular property in an JSON and retrieve a corresponding property [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
use jQuery's find() on JSON object
(6 answers)
Closed 8 years ago.
I am trying to access a particular property of an object , specifically 'levelId' in the following code.
This is what I have so far
FIDDLE
The code goes like this
$(document).ready(function(){
var jsonList = {
"json_data": {
"data": [
{
"data": "A node",
"metadata": {
"id": "23"
},
"children": [
"Child 1",
"A Child 2"
]
},
{
"attr": {
"id": "li.node.id1",
"levelId": "3",
"fmnName": "Ragini"
},
"data": {
"title": "Long format demo",
"attr": {
"href": "#"
}
},
"children": [
{
"data": {
"title": "HQ 50 CORPS"
},
"attr": {
"id": 102,
"parentId": 101,
"fmnId": 194,
"fmnName": "PIVOT CORPS",
"levelId": 1,
"name": "HQ 50 CORPS ",
"isHq": "\u0000",
"susNum": "0415009A",
"modType": "Plain",
"seniorityId": 1,
"wePeNum": "HQ-38 WE 4001/1946/8 (3 DIV)",
"reliefId": 0,
"targetReliefId": 0,
"groupId": 0,
"realOrbatDtlId": 0,
"imgName": "10",
"overlayId": "0415009A",
"symbolCode": "1001001",
"locationName": "BHATINDA",
"nrsName": "BHATINDA"
},
"state": "open"
}
]
},
{
"attr": {
"id": "li.node.id1",
"levelId": "3",
"fmnName": "Rag"
},
"data": {
"title": "Long format demo",
"attr": {
"href": "#"
}
}
},
{
"attr": {
"id": "li.node.id1",
"levelId": "4",
"name": "Skyrbe"
},
"data": {
"title": "Long format demo",
"attr": {
"href": "#"
}
}
}
]
}
}
console.log(JSON.stringify(jsonList,null,4));
var newObject = jsonList.json_data.data;
var listItems= "";
$form = $("<form></form>");
$('#form_container').append($form);
var $selectContainer = $("<select id=\"selectId\" name=\"selectName\" />");
for (var i = 0; i < jsonList.json_data.data.length; i++)
{
if(jsonList.json_data.data[i].hasOwnProperty("attr") && jsonList.json_data.data[i].attr.levelId == 3)
{
listItems+= "<option value='" + jsonList.json_data.data[i].attr.fmnName + "'>" + jsonList.json_data.data[i].attr.fmnName + "</option>";
}
}
$($selectContainer).html(listItems);
$($form).append($selectContainer);
});
The above code is capable of retrieving the levelId only if it is in json_data -> data -> attr. However , the levelId might be nested inside json_data -> data -> children -> attr. How do I go about iterating through this object to fetch levelId even if it's nested deep inside.
Use a nested loop:
var data = jsonList.json_data.data;
for (var i = 0; i < data.length; i++) {
var children = data[i].children;
if (typeof children == 'Object') {
for (var j = 0; j < children.length; j++) {
var levelid = children[j].attr.levelId;
// Do something with this child's levelid
}
}
}

Categories

Resources