If my AJAX call returns something like this:
{
"data": {
"name": "Configuration ID",
"type": "string",
"editor": "editableText"
}
}
And I have a variable defined as:
var editableText = $("<div/>").dynamicTableEditor({
editHandler: function(aData, aContext) {
$("#save-data").html("Saving note: <strong>" + aData + "</strong>");
}
});
Is it possible to have to have a variable so that the output would be:
"name": "Configuration ID",
"type": "string",
"editor": $("<div/>").dynamicTableEditor({
editHandler: function(aData, aContext) {
$("#save-data").html("Saving note: <
strong > " + aData + " < /strong>");
}
})
If you just want the string of
$("<div/>").dynamicTableEditor({
editHandler: function(aData, aContext) {
$("#save-data").html("Saving note: <
strong > " + aData + " < /strong>");
}
})
Then it is possible. You can make it as a string and deserializate it any time you want.
I dont know what the return type of dynamicTableEditor() is. If it is a value which can be converted to a String, like abcde which can be converted to "abced", then the answer is yes.
You need to understand what the JSON is. JSON just make everything as a string. So if there is a variable you cannot convert to a string, then the answer is no.
Related
So more sprcifically, this POST request needs to do the below procedures:
1) To find if all the characters from 2 sets of characters are contained in a third set of characters.
2) The 3 sets of characters are given/inserted as parameters in the body request
3) Caps/ or no Caps does not matter in this case. Same goes for spaces.
4) Example of an input:
{"testees": [ "abc", "cde" ], "subject": "acbcde"}
5) Example of an output:
{
"success": true,
"error": null,
"stack": null,
"result": true
}
I'm working out this API with the use of "POSTMAN".
I found some articles like this one: https://attacomsian.com/blog/ways-to-check-string-contains-substring-javascript
But still, I wasn't able to make it work.
I've tried many different things both here and with the previous POST requests I had to make.
The problems this time are:
1) The type of my input. Should it be an object? Should it be a string? I don't know.
2) But most importantly: How to check if every single character from both the 1st and 2nd set of characters is contained in the 3rd set of characters?
app.post("/api/contained", function (req, res) {
var input = {
testees: toString,
subject: toString
}
input.testees = req.body.testees;
input.subject = req.body.subject;
var output = {
success: false,
error: null,
stack: null,
result: false
}
console.log("Type: " + typeof input.testees + ", Value: " + input.testees + ", Length: " + input.testees.length)
console.log("Type: " + typeof input.subject + ", Value: " + input.subject)
The types should be as you specified them in your example.
{"testees": [ "abc", "cde" ], "subject": "acbcde"}
testees as an Array with both of the sets that you are willing to check and subject as a String that you would like to perform the checks on.
The check mechanism should be relatively simple:
let flag = true;
function checkSet(charsSet) {
const chars = charsSet.split('');
for (let i = 0; i < chars.length; i++) {
const char = chars[i].toLowerCase();
if (!input.subject.toLowerCase().includes(char)) {
flag = false;
break;
}
}
}
const [set1, set2] = input.testees; // Destruct both sets.
checkSet(set1);
// You can check if "flag" is already false here and not run the second check for better performances.
checkSet(set2);
if (flag) {
// Both sets are contained inside the third set.
} else {
// One or more of the sets is not contained inside the third set.
}
I am getting JSON value from my server and it works well. But I want to customize my JSON value. I have two questions:
First, when I get region value, I get it like ["USA"],["Mexico"],["Canada"]. Is there a way I can ignore the double quotes/brackets and just get the strings values like USA, Mexico, Canada?
Second, when I get the regDate value I get the whole data like 2018-10-31T07:53:12.000Z instead, can I ignore some values and get it like 2018-10-31 07:53?
{
"result": "ok",
"data": [
{
"idx": 1,
"region": "[\"USA \", \"Mexico \", \"Canada \"]",
"regDate": "2018-10-31T07:53:12.000Z"
}
]
}
Seems that your region data was double-encoded. In javascript, you'll want to decode that, e.g.
const response = {
"result": "ok",
"data": [
{
"idx": 1,
"region": "[\"USA \", \"Mexico \", \"Canada \"]",
"regDate": "2018-10-31T07:53:12.000Z"
}
]
};
const regions = JSON.parse(response.data[0].region);
For time formatting, you could use the built-in Javascript Date type, such as..
const regDate = new Date(response.data[0].regDate);
const regDatestr =
regDate.getUTCFullYear() + '-' +
regDate.getUTCMonth() + '-' +
regDate.getDate() + ' ' +
regDate.getUTCHours() + ':' +
regDate.getUTCMinutes()
;
If you need more functionality than the built-in, I would recommend date-fns.
You'd save the results of your JSON query to a variable data. Then you'd do this:
var countries = "";
for (var i = 0; i < data[0].region.length; i++) {
countries += data[0].region[i];
}
var time = data[0].regDate.split("000Z");
I"m attempting to build a string in order to put the results in a DataTables table.
I'm taking an array and using regex to get everything in it's own index and my resultant string array is this:
["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"]
One big string array with everything in its own index. Next I'm using a loop and building a string in order to pass it to a datatables table. The result of which SHOULD look like this:
var dataString = [
["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Instead I'm getting this:
var dataString = undefined["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Here is my loop code to build the string from the array:
for(var i = 0; i < routePoints.length-3; i+=3){
console.log(routePoints);
if(i >= 0 && i < routePoints.length - 4){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"],';
}else if(i == routePoints.length - 3){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"]';
}
}
If I simply deleted the "undefined" and paste the code in, the datatabe populates fine, but I cannot see where the undefined is even coming from. Thanks for the second set of eyes!
Usually, the undefined comes from your initialization. I don't see the code here, but you probably have something like:
var dataSetString;
instead, you should always start an empty string as:
var dataSetString = "";
As to why this happens. All uninitialized variables default to undefined. When you use the += operation, it will try to interpret what your are doing (if you have two numbers it will add them, two strings: concatenate). Undefined has no good += operation, so it uses the second part of the operation the string you are passing in. So, it automatically converts the undefined to a string and concatenates the new string to it, ending up with "undefined[blah,blah,blah"
You shouldn't compose a String like that.
It doesn't look like you need a string anyway but a 2D array.
var data = ["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"
];
var dataString = [];
for (var i = 0; i < data.length; i+=3) dataString.push(data.slice(i, i + 3));
console.log(dataString);
// Should you actually need a string, you can use JSON.stringify()
console.log(JSON.stringify(dataString));
Cannot use value from previous object property function starting(); when trying to combine in output below; getting NaN for timeTaken(); function. Presumably starting isn't reporting within that function, any suggestions?
starting : function() {
return this.slow * this.driveTime + " mph ";
},
timeTaken : function() {
return this.starting / this.driveTime + " seconds ";
},
document.getElementById("car").innerHTML = car.starting() + car.timeTaken();
Should I rather try to nest both functions in same one function? I'm open to more optimal methods.
Full object code:
var car = {
cruise: "35",
slow: "5",
stop: "0",
driveTime: "4",
starting : function() {
return this.slow * this.driveTime + " mph ";
},
timeTaken : function() {
return this.starting / this.driveTime + " seconds ";
},
};
That's because this.starting is a function. Basically what you are asking JavaScript to do is "take the starting function and divide it by this.driveTime". This is undefined.
What I'm guessing you want is something like this:
var car = {
cruise: 35,
slow: 5,
stop: 0,
driveTime: 4,
starting: function() {
return this.slow * this.driveTime;
},
timeTaken: function() {
return this.starting() / this.driveTime;
},
toString: function() {
return this.starting() + " mph " + this.timeTaken() + " seconds ";
}
};
console.log(car.toString());
console.log(car.starting());
console.log(car.timeTaken());
Note that I changed starting() and timeTaken() to just return numbers (rather than "x mph" or "x seconds"). This allows you to do math on the results from those functions.
I added the toString() function to make it easier to get a string representation of the data that I'm assuming you wanted to print out.
EDIT: As noted by Peter Behr's answer, you should store cruise, slow stop, and driveTime as numbers rather than strings. I have updated my example to show this.
Further Reading
JavaScript data types and data structures at MDN
Additionally, you're doing math on strings, which isn't a great idea. Make the object properties numbers to begin with.
starting method return a String so divide a string by a number will result as NaN
What goes wrong if 77>602? I tried in IE, Firefox and Chrome
function getMaxValue(data){
var maxValue=0;
for(var i=0;i<data.length;i++){
if(data[i].value>maxValue){
console.log(data[i].value +">"+maxValue);
maxValue=data[i].value;
}
}
console.log("MaxValue:"+maxValue);
return maxValue;
}
I get my data from a json:
[{
"keyword": "User: Allen-P",
"value": "602"
}, {
"keyword": "From: phillip.allen#enron.com",
"value": "598"
},
{
"keyword": "Date: 2001",
"value": "276"
},
{
"keyword": "Subject: Re:",
"value": "228"
},
{
"keyword": "Date: 2001 Apr",
"value": "77"
},
]
Needed to add some useless description for StackOverflow. Please help me;). The json file is a bit bigger and just an example.
Strings are compared alphabetically even if they contain numbers. The character '7' comes after the character '6', alphabetically, so indeed, in terms of strings, "77" > "602".
The solution is to convert them to numbers first:
if(parseFloat(data[i].value) > maxValue){
Or for sake of brevity, the unary + operator will also do this:
if(+data[i].value > maxValue){
You're currently comparing an integer with a string, which doesn't reliably work in this situation.
Either change your JSON and unquote the values, or use the following code instead:
function getMaxValue(data){
var maxValue=0;
for(var i=0;i<data.length;i++){
if(parseInt(data[i].value) > maxValue) {
console.log(data[i].value +">"+maxValue);
maxValue=data[i].value;
}
}
console.log("MaxValue:"+maxValue);
return maxValue;
}
Also read this for reference.
You need to use parseInt(value,10) to convert the value from a string to a number