Why is only part of my json data being logged? - javascript

I am trying to eventually have my json data displayed in a label. However, when I console.log the json data, only the last two objects are displayed. When I pass the data to a label, only the last object is displayed. Thanks in advance for any help!
Here is my code:
var json =
{
"Question:": " What is my name? ",
"Answer:": " James ",
"Question:": " What is my age? ",
"Answer:": " 31 "
};
for (var key in json)
{
if (json.hasOwnProperty(key))
{
console.log(key + " = " + json[key]);
}
}
var label = Ti.UI.createLabel({
text: key + json[key]
});
win3.add(label);

Your issue has nothing to do with Titanium. In JavaScript dictionary you can't have two same keys with different values. To demonstrate where you made mistake, I'll rewrite your first lines:
var json = {};
json["Question:"] = " What is my name? ";
json["Answer:"] = " James ";
// We are fine untill now.
json["Question:"] = " What is my age? ";
json["Answer:"] = " 31 ";
// Here you overwrote values for keys "Question:" and "Answer:" which were set above.
To fix your problem, I'd change your json dictionary into array of dictionaries:
var i, key, label;
var json = [
{
"Question:": " What is my name? ",
"Answer:": " James ",
},
{
"Question:": " What is my age? ",
"Answer:": " 31 "
}
];
for (i in json) {
for (key in json[i]) {
label = Ti.UI.createLabel({
text: key + json[i][key]
});
win3.add(label);
}
}

your json object key is duplicated, javascript does not complain from this, it will just overwrite the first key value with the second value

Related

How to Loop through another index of jquery object

I currently have a jquery object which store all the information of a table cells. When i log the object the following content shows up but when i loop them i only get the first line of the log. Please help me how i can loop the remaining line of the object
Thanks guys, i've got the answer.
function Trigger2(clicked_id) {
var $selectedCells = $('table').tableCellsSelection('selectedCells');
$selectedCells.each(function(i) {
var row = $selectedCells.eq(i).parent().index();
var column = $selectedCells.eq(i).index();
document.getElementById("demo").innerHTML += i + " Row " + row + " Column :" + column + "<br>";
});
}

.replace is not a function - couldn't figure it out [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is a new edit to my question, hopefully it will meet the criteria and be considered eligible.
First, I managed to solve the problem. I will now describe the situation and what I think the solution that solve the problem.
My code gets a string (a call number) as an input, re-formats it, parse it to float, and return the call number location within a given set of ranges.
The code is composed of two functions: 1. formatCallNumber(callNum) which does the text manipulation to the input. 2. SortCallNum(callNumInput) - responsible on the sorting to ranges part.
The problem was in passing values of call number ranges from the sorting function (no.2) to the formatting function (no.1). Although I parsed those values as strings in the sorting function, the .replace function produced an error. The solution that I (think) worked, was to parse the values to strings in the formatting function.
The code of the two functions below is updated and seems to be working as expected:
function 1 - formatting function:
function formatCallNumber(callNum){
var formatedCallNum = String(callNum);
formatedCallNum = formatedCallNum.replace(/\D/g,''); // remove all but digits chars from the string (whitespace, dots, etc)
formatedCallNum = "0." + formatedCallNum; // add "0." to the callNumber string
formatedCallNum = parseFloat(formatedCallNum); // parse as float - so it could be compared with other decimals
return (formatedCallNum);
}
Function 2 - the sorting function:
function SortCallNum(callNumInput){
// data [test only]
var shelves = {
"S1" : {"callStart":"100","callEnd": "223.456", "id": 1},
"S2" : {"callStart":"223.457","callEnd": "334", "id": 2},
"S3" : {"callStart":"335","callEnd": "535", "id": 3},
"S4" : {"callStart":"536","callEnd": "638", "id": 4},
"S5" : {"callStart":"639","callEnd": "847", "id": 5}
};
var matchId = "";
document.getElementById("somthing").innerHTML += "you typed the number: " + callNumInput; // output of callNumInput (as inserted by user)
formatedCallNum = formatCallNumber(callNumInput);
// traverse into shelves object : iteration of objects (key = s1-s5)
for (var key in shelves) {
if (shelves.hasOwnProperty(key)) {
matchId = shelves[key].id;
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallEnd is: " + " -- " + shelves[key].callEnd); // display values of object shelves.key.callend
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallStart is: " + " -- " + shelves[key].callStart); // display values of object shelves.key.callend
var formatedCallRangeStart = formatCallNumber(shelves[key].callStart);
var formatedCallRangeEnd = formatCallNumber(shelves[key].callEnd);
console.log(formatedCallRangeStart);
console.log(formatedCallRangeEnd);
if ((formatedCallNum <= 0) || (formatedCallNum > 1)){alert('call number not in proper range'); break;}
if ((formatedCallRangeStart <= formatedCallNum)&&(formatedCallRangeEnd >= formatedCallNum)){break;}
}
}
Thanks for all the help.
As I can see, everythign should work as expected. It's important to pass a string into SortCallNum, and not a number.
function SortCallNum(callNumInput){
// data [test only]
var shelves = {
"S1" : {"callStart":100,"callEnd": "223", "id": 1},
"S2" : {"callStart":224,"callEnd": "334", "id": 2},
"S3" : {"callStart":335,"callEnd": "535", "id": 3},
"S4" : {"callStart":536,"callEnd": "638", "id": 4},
"S5" : {"callStart":639,"callEnd": "847", "id": 5}
};
var matchId = "";
document.getElementById("somthing").innerHTML += "you typed the number: " + callNumInput; // output of callNumInput (as inserted by user)
formatedCallNum = formatCallNumber(callNumInput);
// traverse into shelves object : iteration of objects (key = s1-s5)
for (var key in shelves) {
if (shelves.hasOwnProperty(key)) {
matchId = shelves[key].id;
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallEnd is: " + " -- " + shelves[key].callEnd); // display values of object shelves.key.callend
document.getElementById("somthing").innerHTML += "<br>" + (" -- " + "CallStart is: " + " -- " + shelves[key].callStart); // display values of object shelves.key.callend
var formatedCallRangeStart = String(shelves[key].callStart);
formatedCallRangeStart = formatCallNumber(formatedCallRangeStart);
var formatedCallRangeEnd = String(shelves[key].callEnd);
formatedCallRangeEnd = formatCallNumber(formatedCallRangeEnd);
matchId = shelves[key].id;
if ((formatedCallRangeStart <= formatedCallNum)&&(formatedCallRangeEnd >= formatedCallNum)){
break;
}
}
}
alert (matchId);
}
function formatCallNumber(callNum){
// callNum = prompt('enter a call number: ');
formattedCallNum = callNum.replace(/\D/g,''); // remove all but digits chars from the string (whitespace, dots, etc)
formattedCallNum = "0." + formattedCallNum; // add "0." to the callNumber string
formattedCallNum = parseFloat(formattedCallNum); // parse as float - so it could be compared with other decimals
return (formattedCallNum);
}
SortCallNum('1337')
<div id="somthing"></div>
So, this would work SortCallNum('1337'), this not SortCallNum(1337)...
Another possible cause is that you trust the return-value from prompt blindly.
<button type="button" onclick="var callNumInput = prompt('enter a call number: '); SortCallNum(callNumInput);"> SortCallNum(test)</button>
When the user clicks the OK button, text entered in the input field is returned. If the user clicks OK without entering any text, an empty string is returned. If the user clicks the Cancel button, this function returns null.
https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#Example
A bit of sanitization should help:
if (callNumInput == null) {
throw new Error('You have to insert a number between 0 and 999.')
}

Push specific, non-repeating value from JSON set into .each statement

I have an each statement like this:
$.each(data, function(i, value) {
sublayers.push({
sql: "SELECT " + firstSel2 + ", cartodb_id, the_geom_webmercator FROM full_data_for_testing_deid_2 where " + firstSel2 + "='" + value.attri_1 + "'",
cartocss: "#full_data_for_testing_deid_2 {marker-fill:"+color_here+";marker-width:5;marker-line-width: 0.2;marker-line-color:#fff;marker-allow-overlap: true;}"
});
});
In the cartocss portion, there's a variable color_here. This is what I need to replace. This needs to be a hex value from an object like this:
var myColors = ["#364C57",
"#666DD6",
"#867EAD",
"#1A3D76",
"#7F787F",
"#35304C",
"#1D5772",
"#15446B",
"#7382C0",
"#484A48",
"#454252",
"#333C6F"];
What I need is for the each statement to pull out one of these colors (starting from the top) for each value that it loops through without repeating. Assume that there will never be more loops than there are colors in my object above. Is there a way to do this that ensures the colors don't repeat for a given each statement? I can come up with something that randomly picks from the list, but it would result in the possibility of a duplicate.
Seems that you need just to select the color from the array according to the current index:
var color_here = myColors[i];
doesn't it? Place it before sublayers.push().
Maybe like this what you want:
var color_curr;
var myColors = ["#364C57",
"#666DD6",
"#867EAD",
"#1A3D76",
"#7F787F",
"#35304C",
"#1D5772",
"#15446B",
"#7382C0",
"#484A48",
"#454252",
"#333C6F"];
$.each(data, function(i, value) {
var color = myColors[i];
if(color!=color_curr){
sublayers.push({
sql: "SELECT " + firstSel2 + ", cartodb_id, the_geom_webmercator FROM full_data_for_testing_deid_2 where " + firstSel2 + "='" + value.attri_1 + "'",
cartocss: "#full_data_for_testing_deid_2 {marker-fill:"+color_here+";marker-width:5;marker-line-width: 0.2;marker-line-color:#fff;marker-allow-overlap: true;}"
});
}
color_curr=color;
});

Javascript - accessing single name value pair not working

Can anyone tell me why this is not working?
var fieldsValid = {
registerUserName: false,
registerEmail: false,
registerPassword: false,
registerConfirmPassword: false
};
function showState () {
var str = "<p>registerUserName: " + fieldsValid[registerEmail] + "</p>" ;
document.getElementById('showstate').innerHTML = str;
}
showState();
There is no output into my div.
Use quotes around the property name because otherwise, registerEmail is treated as a variable containing the property name, not a property name:
var str = "<p>registerUserName: " + fieldsValid['registerEmail'] + "</p>" ;
Or use the . syntax without quotes:
var str = "<p>registerUserName: " + fieldsValid.registerEmail + "</p>" ;
MDN Working With Objects is a good resource, relevant to this.
For future debugging, observe the console (F12) in your browser.
Let's say you have someObject.
someObject[johndoe] Returns the item in someObject that has johndoe's value (since here it is a variable) as index.

Parsing Complex JSON Javascript

I am able to parse JSON that returns simple data, with JSON.parse but I am having trouble with data that returns objects, dates, strings, etc..
var theData=JSON.parse(theData);
Something like this JSON.parse returns [Object] object back with no data at all (I can see the data is being successfully returned because it returns all the data as a string if I have JSON.parse turned off).
{
"AppName": "TheName",
"AppUrl": "https:\/\/app\/icons\/unknown.png",
"aGUID": "45c055d2-2edc-d4444"."DateCreated": "8\/23\/2012 11:04AM", {
"ID": "yser123",
Name ":" User "}
}
What is the best way to go about parsing this data in javascript(I am not able to use jquery)?
Note: I had wrote the JSON assume its valid
Here is the code I am using to retreive the data..
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "ClientService.svc/REST/GetDetail", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
return serverResponse;
First and foremost, don't use synchronous XHR. Rewrite your JavaScript to be asynchronous.
function getDetail(cb) {
var xhReq = new XMLHttpRequest();
xhReq.open("POST", "ClientService.svc/REST/GetDetail", true);
xhReq.onreadystatechange = function() {
if (xhReq.readyState == 4) cb(xhReq.responseText);
}
xhReq.send(null);
}
// to call:
getDetail(function(data) {
JSON.parse(data);
}
Second, your problem is not that JSON is being parsed incorrectly. It's your debugging call to alert. When you pass the serverResponse object, alert coerces the object into a string by calling the object's toString method, which simply returns '[object Object]'.
Try console.log. Objects can be inspected in the console.
It actually sounds like this is working. If you call some thing like this:
alert(JSON.parse(serverResponse))
It will display [object Object] which is correct. If you call
alert(JSON.parse(serverResponse).appName)
You should see the appName. If you are not seeing "SyntaxError"s being thrown, JSON.parse() is working
Your JSON format is wrong and the data needs to be a string.
So, this will work (I broke the lines to improve readability):
var data = "{" +
" \"AppName\": \"TheName\", " +
" \"AppUrl\": \"https:\/\/app\/icons\/unknown.png\", " +
" \"aGUID\": \"45c055d2-2edc-d4444\", " +
" \"DateCreated\": \"8\/23\/2012 11:04AM\", " +
" \"foo\": { " +
" \"ID\": \"yser123\", " +
" \"Name\":\"User\"" +
" }" +
"}";
var obj = JSON.parse(data);
alert( obj.AppName );
Of course, if you use simple quotes as string delimiter, the code would be:
var data = '{' +
' "AppName": "TheName", ' +
' "AppUrl": "https:\/\/app\/icons\/unknown.png", ' +
' "aGUID": "45c055d2-2edc-d4444", ' +
' "DateCreated": "8\/23\/2012 11:04AM", ' +
' "foo": { ' +
' "ID": "yser123", ' +
' "Name":"User"' +
' }' +
'}';
This not works:
var data = "{" +
" 'AppName': 'TheName', " +
" 'AppUrl': 'https:\/\/app\/icons\/unknown.png', " +
" 'aGUID': '45c055d2-2edc-d4444', " +
" 'DateCreated': '8\/23\/2012 11:04AM', " +
" 'foo': { " +
" 'ID': 'yser123', " +
" 'Name': 'User'" +
" }" +
"}";
jsFiddle: http://jsfiddle.net/9pmdm/1/

Categories