if statement breaking .push method - javascript

So I'm looping through a set of JSON arrays, and then looping through each individual array.
If I remove the two if statements it will loop through both data sets and append the 'target' with both 'data' sets, but like it is now, it will only append the items.join through the first each loop.
The case stuff was an if loop first, thinking it would matter, but no.
Strange thing is, the consoleOut (like console.log) does print my stuff, so It actually does loop through both arrays within the JSON set.
$.each(data, function(keys, vals)
{
var items = [];
$.each(data[keys], function(key, val)
{
var currString = JSON.stringify(val);
switch (key)
{
case "ID":
consoleOut("ID: "+currString+" loaded");
break;
case "parentIDs":
consoleOut("parentIDs: "+currString);
break;
case "UID":
consoleOut("UID: "+currString);
UID = unquote(currString);
break;
case "title":
consoleOut("Title: "+currString);
items.push('<H1 class="' + key + '">' + unquote(currString) + '</H1>');
break;
case "img":
consoleOut("IMG: "+currString);
if ($(currString).val() !== '')
{
items.push('<IMG class="' + key + '" src='+currString+'></IMG>');
};
break;
case "text":
consoleOut("TXT: "+currString);
if ($(currString).val() !== '')
{
items.push('<P class="' + key + '">'+currString+'</P>');
};
break;
}
});
consoleOut("---------");
$('<DIV/>', {
'id': UID,
html: items.join('')
}).appendTo(target);
}
)
I'm wondering how the if statements are breaking my appending to the main 'items' array..
(When I don't stringify the val at the beginning it will loop, but that's because the if statements are then true, but stop working when false.. So maybe It's better to modify my if statement for that, but I'm still puzzled as to how the .push stops working?)

$(currString).val()
It is saying you are making an element and looking at the value attribute of that element. Is that what you really want? I do not think image or text has a value.
I would think you would want to use length or html()
[EDIT] Looking at your object, you just want to check the lenght of currString
if( currString && currString.length>0 ) {

This is not JSON, it is an array.
[{"ID":"1",
"parentIDs":null,
"UID":"home",
"title":"Home",
"text":"<3 here",
"img":"/favicon.ico",
"url":"home",
"cat_id":"1",
"view_id":"",
"css_id":null}‌​,
{"ID":"4",
"parentIDs":"home",
"UID":"home_info",
"title":"Info about Home",
"text":"Info about Home",
"img":"",
"url":"",
"cat_id":"",
"view_id":"",
"css_id":null}
]
Are you sure your input does not look something like this (ie, is JSON)?
{ "data" : [{"ID":"1",
"parentIDs":null,
"UID":"home",
"title":"Home",
"text":"<3 here",
"img":"/favicon.ico",
"url":"home",
"cat_id":"1",
"view_id":"",
"css_id":null}‌​,
{"ID":"4",
"parentIDs":"home",
"UID":"home_info",
"title":"Info about Home",
"text":"Info about Home",
"img":"",
"url":"",
"cat_id":"",
"view_id":"",
"css_id":null}
] }

Related

Convert JSON to HTML: Uncaught TypeError: json.forEach is not a function

I want to convert JSON to HTML to display it on website. I've googled, and this error occurs when when json is a string, and first I need to parse. But when I use JSON.parse, the console says it is already an object (Unexpected token o in JSON at position 1).
$(document).ready(function() {
$("#getMessage").on("click", function() {  
$.getJSON("http://quotes.rest/qod.json", function(json) {
var html = "";
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'blabla'>";
keys.forEach(function(key) {
html += "<b>" + key + "</b>: " + val[key] + "<br>";
});
html += "</div><br>";
});
$(".message").html(html);
});
});
});
json is an object, not an array. You can use forEach only on arrays.
As you have done already, you can iterate over the object's keys like this:
Object.keys(json).forEach(function(key) {
var value = json[key];
...
});
In addition to what everyone else said, it appears that the JSON response does not look like you think it does.
var json = {
"success": {
"total": 1
},
"contents": {
"quotes": [{
"quote": "It's not whether you get knocked down, it...s whether you get up.",
"length": "65",
"author": "Vince Lombardi",
"tags": [
"failure",
"inspire",
"learning-from-failure"
],
"category": "inspire",
"date": "2016-08-09",
"title": "Inspiring Quote of the day",
"background": "https://theysaidso.com/img/bgs/man_on_the_mountain.jpg",
"id": "06Qdox8w6U3U1CGlLqRwFAeF"
}]
}
};
var messageEl = document.querySelector('.message');
messageEl.innerText = json.contents.quotes[0].quote;
<div class="message"></div>
$.getJson already transforms a JSON object into a javascript object, so you would not need to parse it again.
However, your problem starts with forEach, which is an Array method, not an Object method, therefor it will not work in your use case.
var jsonKeys = Object.keys(json); jsonKeys.forEach(...) will work, as Object.keys returns an array of Object keys.

How to separate a JSON.stringify result

Related Retrieve two lists, sort and compare values, then display all the results
The question in the related post was how to combine two lists and sort them. The code referenced each item on each list. So, when I got the result, I could manipulate it.
The best solution used console.log(JSON.stringify(result,null,2)); to return the result, nicely combined and sorted.
Trouble for me is being able to translate that back into something I can work with. I can get the result into a variable and display it on the page, but it's the raw output : [ { "Title": "apple", "Type": "rome", "State": null }, ...
Have tried 'JSON.parse(result);' where result is the variable that is used to handle the combination and sorting of the two lists. All that gives is an invalid character error on the line. Also looked at the 'replace' option. That just confused me, tmi. Tried setting a variable directly on the result (so those who know are laughing) 'var foo = result;' That returns object, object.
The desired end result would be to end up with each item separate so I can put them in a table (or a list) on my html page with blanks in any column where there is no data.
I know there has to be a simple, easy way to do this without 200 lines of transformation code. But I can't find a clear example. Everything I'm seeing is for +experts or uses a super simple array that's typed into the code.
Is there a way to attach something like this (from my original) to the result instead of using JSON.stringify? What other step(s) am I missing in being able to extract the fields from JSON.stringify using JSON.parse?
}).success(function (data) {
var title = '';
var type = '';
$.each(data.d.results,
function (key, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
$("#tdtitle").html(title);
$("#tdtype").html(type);
Terry, you wrote: "All that gives is an invalid character error on the line"? Then result is not a valid json. Test it here: http://jsonlint.com/, fix it, then try again.
var data = {
d:{
results: [
{ "Title": "apple", "Type": "rome", "State": null },
{ "Title": "grape", "Type": "fruit", "State": null }
]
}
};
var title = '';
var type = '';
$.each(data.d.results, function (index, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
alert(title + type);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript, check if current part object is inside other part object

I am trying to loop over an object and check if a certain property is inside any other certain parts of the object. I am trying to see if the first level.parentSearch is inside any of the other firstlevel.filters array (of objects).
So my object looks like this for example :
var currentfilters = [{
"id": "topics",
"name": "Topics",
"filters": [{
"id": "isSubTopic",
"label": "isSubTopic",
"search": "isSubTopic",
"num": 15
}]
}, {
"id": "isSubTopic",
"name": "isSubTopic",
"parentSearch": "isSubTopic",
"filters": [{
"id": "subtopicFilter",
"label": "subtopicFilter",
"search": "subtopicFilter",
"num": 2
}, {
"id": "subtopicFilter1",
"label": "subtopicFilter1",
"search": "subtopicFilter1",
"num": 2
}]
}, {
"id": "notSubTopic",
"name": "notSubTopic",
"parentSearch": "uniueParentSearch",
"filters": [{
"id": "notSubTopic1",
"label": "notSubTopic1",
"search": "notSubTopic1",
"num": 5
}]
}
];
So what I am trying to achieve is to loop over this object and modify it a little bit (if necessary) and return it. What I am trying to do is check the first level if the .parentSearch property is inside any of the other objects .filter array as a .search property. So in this example isSubTopic would be what I am looking for, because it is inside the Topics filters array.
This is my first time trying these kind of problem, so if I am missing anything please let me know. I figured since I want to return a modified object, it would be good to reduce this object and check inside. The part I am struggling with is the bit that checks if my current parentSearch (in the reduce loop) is in any other objects filter array (under the .search property). I have lodash to mess around with so I have tried both _.find and _.has, but I think I am not approaching this correctly. Any/all input would be greatly appreciated!
Here is what I was trying it with : https://jsfiddle.net/0fttkyey/32/
function checkIfSubtopic(memo, value, key) {
if(value.parentSearch) {
//check if value.parentSearch is in any of the value.filters
console.log("find?", _.find(currentfilters, value.parentSearch));
if(_.find(currentfilters, value.parentSearch)){
console.log("is subtopic?");
} else {
console.log("not sub topic");
}
}
return memo;
}
Interestingly, your currentfilters is not the same in the jsfiddle you provide, so it gives no result.
If I understand correctly, what you try to achieve is:
For each "filter" in currentfilters array, check if parentSearch member is truthy.
If so, loop through all other filters.
For each of these filters, loop through its filters array member.
If the search member of one of the objects in this filters array is equal to parentSearch value, keep the current "filter".
So you have 3 nested loops.
The 2 outer loops iterate over the same currentfilters array, except that the 2nd (inner) one skips the filter which parentSearch value is being searched for.
As soon as parentSearch value is found, break loops 2 and 3 (the 2 inner-most) and go to next item of 1st (outer-most) loop.
Without using lodash and building a new result array (instead of modifying currentfilters array in place which may yield unexpected results), you would have for example:
var i = 0,
j,
ifiltermax = currentfilters.length,
currentParentSearch,
currentFiltersArray,
k,
result = [];
for (; i < ifiltermax; i += 1) { // Loop 1.
currentParentSearch = currentfilters[i].parentSearch;
if (currentParentSearch) { // If `parentSearch` is truthy.
loop_j: for (j = 0; j < ifiltermax; j += 1) { // Loop 2.
if (j != i) { // Skip current filter which `parentSearch` is being searched for.
currentFiltersArray = currentfilters[j].filters;
for (k = 0; k < currentFiltersArray.length; k += 1) { // Loop 3.
if (currentFiltersArray[k].search === currentParentSearch) {
result.push(currentfilters[i]); // Keep current "filter".
console.log("Found " + currentParentSearch + " (from item #" + i + ") in item #" + j + ", filter #" + k);
break loop_j; // Break loops 2 and 3.
}
}
console.log("Did not find " + currentParentSearch + " (from item #" + i + ") in any other filter.");
}
}
}
}
console.log(result);
Updated jsfiddle: https://jsfiddle.net/0fttkyey/71/ (with currentfilters from the question above, instead of the one in jsfiddle version 32).

displaying json data in javascript not working

I have created a var and passed JSON data(comma seperated values) to it, but when I want to display json data - it only returns null. Here's the code:
<script type="text/javascript">
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
document.write(data1);
</script>
You can either do it like this:
var data1 = [{order:"145",country:"Dubai",employee:"permanent",customer:"self"} ];
data1.forEach(function(data){
document.write(data.order);
document.write(data.country);
document.write(data.employee);
document.write(data.customer);
});
or you can do it like this
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
$.each(data1[0], function(key, value){
document.write(key + " " + value);
});
Either way, storing just one object in the list makes this answer a bit redundant unless I show you how to loop over multiple objects.
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
data1.forEach(function(data){
$.each(data, function(key, value){
document.write(key+" "+value);
});
});
I'm using a mix of jQuery here aswell, which might not be optimal but atleast it serves to show that there are multiple ways to accomplishing what you need.
Also, the forEach() method on arrays is a MDN developed method so it might not be crossbrowser compliant, just a heads up!
If you want pure JS this is one of the ways to go
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
for(json in data1){
for(objs in data1[json]){
document.write(objs + " : " + data1[json][objs]);
}
}
For simple and quick printing of JSON, one can do something like below and pretty much same goes for objects as well;
var json = {
"title" : "something",
"status" : true,
"socialMedia": [{
"facebook": 'http://facebook.com/something'
}, {
"twitter": 'http://twitter.com/something'
}, {
"flickr": 'http://flickr.com/something'
}, {
"youtube": 'http://youtube.com/something'
}]
};
and now to print on screen, a simple for in loop is enough, but please not e, it won't print array instead will print [object Object]. for simplicity of answer, i won't go in deep to print arrays key and value in screen.
Hope that this will be usefull for someone. Cheers!
for(var i in json) {
document.writeln('<strong>' + i + '</strong>' +json[i] + '<br>');
console.log(i + ' ' + json[i])
}

Creating Dynamic variables from json response

My JSON response looks like this :
{"sample":[{"id":"2","name":"branch name"},{"id":"3","name":"branch name 2"}]}
My function looks like this :
function getJSONObjects(){
$.getJSON("http://localhost/api/branches",
function(data){
$.each(data.sample, function(i,item){
var loc = "branch";
eval("var " + loc + item.id + "=123;");
alert(loc + item.id);
});
});
}
The idea is to create branch + id object so I can do something with it(create marker on a map), so I tried to assign it any value to see if this was working.
I wanted both branch2 and branch3 to alert 123 so I have something to start with. But currently this alerts branch2 and branch3 instead of 123.
I have little experience with creating dynamic variables/objects can someone tell me what I'm doing wrong or maybe another approach towards solving this?
No idea what you want to do here:
eval("var " + loc + item.id + "=123;"); // eval is EVIL
alert(loc + item.id); // just creates a string...
Creating dynamic variables is a bad idea. Rather create an object and use key/values.
var branches = {}; // new object, move this to the scope you want to access the value from later
branch[item.id] = 123; // set the key 'item.id' to the value '123'
console.log(branch[item.id]); // retrieve the value of the key 'item.id'
But if you're doing this you can just as well change the structure of your JSON data to something like this:
{"sample":[{"1": {"name": "branch name1", "value": 123}, "2": {"name": "branch name2", "value": 456}}]}
Then just grab the elements of the array and use them like branches above.
Try the following function to iterate data.sample:
function(i,item){
window[loc + item.id] = 123;
alert(window[loc + item.id]);
}
The window object here is used to set a global variable, "dynamically" named on runtime. (This is not a good practice, though.)
If loc = 'branch' and item.id = 2, the alert(window[loc + item.id]) statement would be equivalent to alert(branch2).

Categories

Resources