Unable to get the value from json object in javascript - javascript

unable to get the value_1 from dataObject.Showing undefined.
var errorMessage;
var dataObject ={"project_type":"{\"value_1\":\"Ground Mount\"}"};
var project_type_str = dataObject['project_type'];
project_type_str = JSON.stringify(project_type_str);
if (project_type_str != null && project_type_str.length != 0) {
errorMessage = '';
} else {
errorMessage = 'Please select a project type';
}
alert(project_type_str);
var responseJson = {};
var project_type_obj = JSON.parse(project_type_str);
alert(project_type_obj);
var value = project_type_obj["value_1"];
alert(value);
Thanks for your answers.Please help me

project_type_str is already a string, so no need to JSON.stringify it.
The code should work fine if you remove the line
Remove this line
project_type_str = JSON.stringify(project_type_str);
A comparison for your better understandability
With original code
With the line removed

You don't need those extra quotes and escape characters to define the object. Do this:
var dataObject = {
"projectType": {
"value1": "groundMount"
}
};
EDIT: I now see that you were intentionally writing JSON in its string representation so that you can parse it later. I hope that you have a special use case where you'd need to do something like that; otherwise, defining the object like I have will be much easier to deal with.

Related

JSON.parse() not working in javascript in pentaho

I am trying to form an array from a string using Modified Java Script Value step. Here is my code to parse a string and to form a JSON object.
var info = {};
var keywords = 'Adjust course (C-6),Identify underlying factors (C-4),Isolate teacher actions (C-3_)';
if(keywords != null && keywords != ''){
keywords = keywords.replace(/,/g,'","');
keywords = '["'+keywords+'"]';
info.keywords = JSON.parse(keywords);
}
Here in JSON.parse() it throws an error SyntaxError: Missing comma in array literal.
Can anyone please help me parse the array and store in json object.
Thanks in advance!
Try this one
if(keywords){
keywords = keywords.split(',');
info.keywords = keywords;
}
Try this:
function kwInfo(text)
{
return JSON.parse('["' + (text || '').split(',').join('","') + '"]');
}
var text = 'Adjust course (C-6),Identify underlying factors (C-4),Isolate teacher actions (C-3_)';
var info = {keywords:kwInfo(text)};
console.log(info);
Run kettle in console mode SpoonConsole.bat
var info = {};
var keywords = 'Adjust course (C-6),Identify underlying factors(C-4),Isolate
teacher actions (C-3_)';
java.lang.System.out.println("Original : " + keywords);
if(keywords != null && keywords != ''){
keywords = keywords.replace(/,/g,'","');
java.lang.System.out.println("Regexp applied : " + keywords);
keywords = '["'+keywords+'"]';
java.lang.System.out.println(keywords);
info.keywords = JSON.parse(keywords);
}
Look into console and trace the error in logic
This is only way I found to trace JavaScript step

AngularJS - Programmatically check whether filter exists

Is there a way to programmatically check whether a filter with a given name exists?
I developed a directive to process page content based on a string input, I want it to react differently in case a certain part of the string corresponds to a filter that exists in my system. For example I have a localize filter:
// Somewhere in the code
var myInput = 'localize';
// Somewhere else
var contentToProcess = 'my content';
var result = '';
if ($filter.hasOwnProperty(myInput)) // TODO: this is the part I'm trying to figure out
result = $filter(myInput)(contentToProcess);
else
result = 'something else';
Jonathan's answers is also acceptable, but I wanted to find a way to check if a filter exists without using a try catch.
You can see if a filter exists like this:
return $injector.has(filterName + 'Filter');
The 'Filter' suffix is added by angular internally, so you must remember to add it or you will always return false
Solution
This seems to work for me.
var getFilterIfExists = function(filterName){
try {
return $filter(filterName);
} catch (e){
return null;
}
};
Then you can do a simple if check on the return value.
// Somewhere in the code
var myInput = 'localize';
var filter = getFilterIfExists(myInput);
if (filter) { // Check if this is filter name or a filter string
value = filter(value);
}
Bonus
If you are looking to parse apart a filter string for example 'currency:"USD$":0' you can use the following
var value; // the value to run the filter on
// Get the filter params out using a regex
var re = /([^:]*):([^:]*):?([\s\S]+)?/;
var matches;
if ((matches = re.exec(myInput)) !== null) {
// View your result using the matches-variable.
// eg matches[0] etc.
value = $filter(matches[1])(value, matches[2], matches[3]);
}
Pull it all together
Wish there was a more elegant way of doing this with angular however there doesn't seem to be.
// Somewhere in the code
var myInput = 'localize';
var value; // the value to run the filter on
var getFilterIfExists = function(filterName){
try {
return $filter(filterName);
} catch (e){
return null;
}
};
var filter = getFilterIfExists(this.col.cellFilter);
if (filter) { // Check if this is filter name or a filter string
value = filter(value);
} else {
// Get the filter params out using a regex
// Test out this regex here https://regex101.com/r/rC5eR5/2
var re = /([^:]*):([^:]*):?([\s\S]+)?/;
var matches;
if ((matches = re.exec(myInput)) !== null) {
// View your result using the matches-variable.
// eg matches[0] etc.
value = $filter(matches[1])(value, matches[2], matches[3]);
}
}
You can just do this:
var filter = $filter(myInput);
if (filter)
result = filter(contentToProcess);
else
result = 'something else';
Undefined and null values are treated as false in JS, so this should work in your case.

Combining two object in javascript and convert to String

I am hoping I am missing something obvious here, but I have tried for the past half day to set two variables to combine in a certain format in Javascript I can do it as a string, however I need it in a different format.
If I select on option from the check boxes {"GILLS":"7"} works fine however if two options are selected query1 should look like [{"GILLS":"1"},{"GILLS":"7"}]. I cannot use += to the variable as this kicks out an unexpected token error.
var Query1 = '';
var Query3 = '';
if ($('input[name=checkbox2a]:checked').length > 0) {
var Query3 = {"GILLS":"7"};
}
if ($('input[name=checkbox2b]:checked').length > 0) {
var Query3 = {"GILLS":"1"};
}
Try
var Query1 = [];
and in your function use
Query1.push({"GILLS":"1"})
So the change will be like below
var Query1 = [];
var Query3 = [];
if ($('input[name=checkbox2a]:checked').length > 0) {
Query3.push({"GILLS":"7"});
}
if ($('input[name=checkbox2b]:checked').length > 0) {
Query3.push({"GILLS":"1"});
}
then you can use join will give you string
Query3.join(", ")
Make an array out of Query3, if you still want a string at the end, use .join("").
var Query1 = '';
var Query3 = [];
if ($('input[name=checkbox2a]:checked').length > 0) {
Query3.push({"GILLS":"7"});
}
if ($('input[name=checkbox2b]:checked').length > 0) {
Query3.push({"GILLS":"1"});
}
Query3 = Query3.join(""); // back to string, if you so like
You're causing pain for yourself if you take the approach that sometimes the variable is of type Object ({"GILLS": "1" }) and sometimes it is of type List ([{"GILLS":"1"},{"GILLS":"7"}]).
Since it sometimes needs to be a list, make sure it's always a list. Even though sometimes it's a list of length 1. Then when you are reading that value, you never need conditional logic to deal with two potential types.
So, it's always a List:
var query3 = [];
... and then it's easy to manipulate:
if(...) {
query3.push( { "GILLS": "7" } );
}
if(...) {
query3.push( { "GILLS": "1" } );
}
At first, you are declaring same variable in a different scope. Don't do this unless uou know what you are doing. In other words use var keyword only once for a variable in a "space" when you are using this particular variable.
An advantage/disadvantage (chose one ;)) of javascript is that there is no type control. If You type var Query3 = ''; and then Query3 = {"GILLS":"7"}; interpreter will execute this without any complaints beside that there is high probability, that this is not exactly what you want to do ;). In this case it makes variable Query3 an empty string and then makes it an object.
In Your case, You want to have in result an array of objects. At first declare var Query3=[]; and then use a push method on it (Query3.push({});) to add elements.

got stuck with this set of code in jquery validate

var formRules = $(this).data('rules');
var formValues = $(this).data('values');
if(formRules || formValues){
var rulesArray = formRules.split(',');
var valuesArray = formValues.split(',');
for(var i=0; i < rulesArray.length; i++){
//alert(rulesArray[i]);
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
}
}
else{
return false;
}
This throws an error like following
Error: TypeError: $.validationEngine.defaults.rulesArray is undefined
Source File: http://localhost:8380/javascript/jquery.validationEngine.js
Line: 2092
I cannot find the problem with this code.Any help is welcome
EDIT:
I am trying to set the global options eg:scroll using the for loop.
The formRules string will have these options comma seperated and the corresponding values in the formValues string.
So i am expecting it to come like $.validationEngine.defaults.scroll = true;
change this line
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
to this
$.validationEngine.defaults[rulesArray[i]] = valuesArray[i];
rulesArray is not a child of $.validationEngine.defaults. The values stored in your rulesArray are. The syntax in my second code block references everything properly.
This is called Bracket Notation, a way to get an object's property using any sort of valid calculation (like rulesArray[i], or "myStringPropertyName"). see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators for other methods.

Javascript objects matching

A Javascript object can be used as an associative array.
So my question is how can I automatically set that multiple key's with the same ending match one value?
I'll write an example to be more explicit on what I want.
Something like this:
var handle = {}
handle[*css] = handlers.style;
Every key that ends with "css" should be matched to handlers.style.
Any way to doing this?
PD: Im doing this with server-side javascript with NodeJS
This is possible if you iterate through the object properties and check that the property name matches the desired pattern. Something like:
for (var i in obj) {
if (i.toString().substr(-3) === 'css') {
obj[i] = handlers.style;
}
}
A quick and dirty way:
var handle = {}
name = "article_users_css"
handle[name.substr(name.length-3)] = "something"
or if you can use some symbol to delimit the suffix, you can use this instead:
name.substr(str.lastIndexOf(YOUR_CHAR_OF_CHOICE))
I don't think you can do this. But you can the request pathname before routing the request to your handlers.
See example below:
var path = "mystyle.css"
// var path = "index.html"
// var path = "image.png"
var handle = {};
handle[css] = handlers.style;
handle[html] = handlers.html;
handle[img] = handlers.img;
if (path.match(/.*\.css/)) {
handle[css]();
}
else if (path.match(/.*\.html/)) {
handle[html]();
}
else if ((path.match(/.*\.png/) || path.match(/.*\.jpg/)) {
handle[img]();
}
You can consider using Express that does support routing based on regEx matching

Categories