Splitting up a string and passing it to a function - javascript

I am having some trouble trying to pass string objects to a function. In the query string of the url I pass fields which is a comma delimited string containing the attributes of interest.
I put the names of those attributes in the fields array. However now I am having trouble passing that information to a function.
In the code below the query.pluck('id', 'name') works, the query.pick( fieldString ) does not.
I am stuck on this one, how can I pass the attribute names in the fields array to the function so it will work?
Please advice.
var log = require('logule').init(module,'query');
var url = require('url');
module.exports = {
build : function(req, entity, callback) {
var isCollection;
isCollection = req.params.id? false: true;
var query = req.rethink.table(entity);
parsedUrl = url.parse(req.url, true);
console.log(isCollection);
if (parsedUrl.query.fields) {
var fields = parsedUrl.query.fields.split(',');
var total = fields.length;
fieldString = fields[0];
for (var i = 1; i < total; i++) {
fieldString += ', ' + fields[i];
}
if (isCollection) {
var query = query.pluck('id', 'name');
} else {
var query = query.get(req.params.id).pick( fieldString );
}
}
return callback(null, query);
}
}

You don't need to put fields in a string, just use
var query = query.get(req.params.id).pick.apply(this,fields);

You need to use the "apply" function with the function name, and an array of parameters (fields in your case)
var query = query.get(req.params.id).apply('pick', fields);

Related

How do I use two variables in my function?

So I have multiple script. One script retrieves data from a Googlesheet and parses it as JSON. The other one uses this to output it to HTML.
My first:
function getStatistics() {
var sheet = SpreadsheetApp.openById("ID");
var rowsData = sheet.getRange("A:A").getValues();
var result = JSON.stringify(rowsData);
var funcNumber = 1;
return result;
}
This retrieves the data from a spreadsheet in column A.
The second script, here I want to use both 'Result' and 'Funcnumber' in my function.
function onSuccess(data, funcNumber) {
var dataJson = JSON.parse(data);
var newColumn = document.createElement("div");
newColumn.className = "column";
for(var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
Using the Json result to PARSE the HTML works. But retrieving 'funcNumber' from the function not. Then finally I call the first function with this line:
google.script.run.withSuccessHandler(onSuccess).getStatistics();
Does anybody know how to use both result and funcNumber in my second function?
function getStatistics() {
var ss = SpreadsheetApp.openById("ID");
const sheet = ss.getSheetByName('Sheet1');
let result = {data:JSON.stringify(sheet.getRange(1,1,sheet.getLastRow(),1).getValues()),funcNumber:1}
return result;
}
function onSuccess(obj) {
var dataJson = JSON.parse(obj.data).flat();
var newColumn = document.createElement("div");
newColumn.className = "column";
for (var i = 0; i < dataJson.length; i++) {
if (dataJson[i] != "") {
var div = document.getElementById('cont-' + obj.funcNumber);
var newDiv = document.createElement("div");
newDiv.innerHTML = dataJson[i];
newColumn.appendChild(newDiv);
}
}
div.appendChild(newColumn);
}
A single column or row is still a 2d array
Following is the way to make the call in Google script to return the value for the 2nd parameter.
google.script.run
.withSuccessHandler(onSuccess)
.withUserObject(funcNumber)
.getStatistics()
WithUserObject() needs to be called after the withSuccessHandler.
See the documentation below on Google script
withUserObject(object)
Sets an object to pass as a second parameter to the success and failure handlers. This "user object" — not to be confused with the User class — lets the callback functions respond to the context in which the client contacted the server. Because user objects are not sent to the server, they are not subject to the restrictions on parameters and return values for server calls. User objects cannot, however, be objects constructed with the new operator.

assigning data to dynamic list variable in javascript

I have requirement where I need to create dynamic json data.
For which i will get two values, columnName and columnValue
var filterJsonColumns = [];
var genericFilter = function (columnName , columnValue) {
if (filterOn != "") {
$scope.filterJsonColumns[columnName ].push(columnValue);
}
console.log("$scope.filterJsonColumns", $scope.filterJsonColumns);
}
For this case I am using dynamic variable for the creation of JSON
ColumnName can have either status or stage or both.
So for in this case JSON should be like
JSON
filterJsonColumns={"status":["1","2"],"stage":["4","5"]}
This JSON formatting is not proper, but still I need this type of data.
Try This
var filterJsonColumns = {};
var genericFilter = function (columnName , columnValue) {
if (filterOn != "") {
if(!filterJsonColumns[columnName]){
filterJsonColumns[columnName] = [];
}
filterJsonColumns[columnName].push(columnValue);
}
console.log("filterJsonColumns",filterJsonColumns);

Javascript : How to concat string to object?

I have following code where i combine some variables to create path to the another existing object and his attribute.
Problem is that i alway get only string, so i would like to "convert" it into the object.
// SET CUSTOM CONTENT FOR COLUMN IF CONTACT ATTR IS EXISTS
if(value.concatByFields != null) {
preparedGridColumnItem.template = function (responseData) {
var nameForConcat;
var fieldName;
var objectName;
var pathToReturn;
$.each(value.concatByFields, function( index, concatField ) {
nameForConcat = null;
fieldName = null;
objectName = null;
objectName = value.field;
fieldName = concatField.fieldName;
console.log("FIELD NAME IS");
console.log(JSON.stringify(fieldName));
console.log("OBJECT NAME IS");
console.log(objectName);
nameForConcat = objectName+"."+fieldName;
console.log("CONCATED NAME IS");
console.log(nameForConcat);
console.log("OBJECT ADDRESS IS FOLLOWING");
console.log("responseData."+nameForConcat);
pathToReturn = "responseData."+nameForConcat;
});
//TODO : IS ALWAYS RETURNED AS STRING
return pathToReturn;
};
}
Returned value should be value of another and global existing json object. But now is it always string.
It means:
responseData.SomeObject.surname
How can i solve it please?
Many thanks for any help.
if(value.concatByFields != null) {
preparedGridColumnItem.template = function (responseData) {
var fieldName;
var objectName;
var pathToReturn;
$.each(value.concatByFields, function( index, concatField ) {
objectName = value.field;
fieldName = concatField.fieldName;
pathToReturn = responseData[objectName][fieldName];
});
//TODO : IS ALWAYS RETURNED AS STRING
return pathToReturn;
};
}

retrieve value in unnamed json array url

I'm struggling to retrieve some value on a json in this url:
http://go-gadget.googlecode.com/svn/trunk/test.json
the url data looks like this:
[
{
"key":{
"parentKey":{
"kind":"user",
"id":0,
"name":"test 1"
},
"kind":"smsgateway",
"id":5707702298738688
},
"propertyMap":{
"content":"test1 content",
"date":"Dec 12, 2013 2:58:57 PM",
"user":"test1"
}
}]
By ignoring the "key", I want to access the value of "propertyMap" object (content,date and user) using javascript code.
I have tried this code but it couldn't get the result:
var url = "http://go-gadget.googlecode.com/svn/trunk/test.json";
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
var content = json[i].propertyMap.content;
console.log('content : ', content);
var user = json[i].propertyMap.user;
console.log('user: ', user);
var date = json[i].propertyMap.date;
console.log('date : ', date);
}
});
(unsuccessful code here http://jsfiddle.net/KkWdN/)
considering this json can't be change, is there any mistake I've made from the code above or there's any other technique to get the result?
I just learn to use javascript and json for 1 month so response with an example is really appreciated.
--edited: I change [].length to json.length, now I'm looking for the answer to access the url
That would be something like :
$.getJSON("http://go-gadget.googlecode.com/svn/trunk/test.json", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.content;
var user = map.user;
var date = map.date;
$('#date').text(date);
$('#nohp').text(user);
$('#content').text(content);
}
});
But the request fails, as no 'Access-Control-Allow-Origin' header is present on the requested resource, so you're being stopped by the same origin policy
What do you think [].length; would evaluate to .
It is 0 , so it would never go inside the for loop.
Other than that you code looks ok.
Replace your for loop as below
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
Also you seem to be accessing a API as part of the different domain.
So you need to use CORS or JSONP to get this working if you want to retrieve data from a different domain.
Change:
for (var i = 0; i < [].length; i = i + 1) {
to
for (var i = 0; i < json.length; i = i + 1) {
DEMO here.
How about using something like the following
In your case, say the object is myObj, I would get the value like this
var content = fetchValue(myObj, [0, "propertyMap", "content"], "");
var date = fetchValue(myObj, [0, "propertyMap", "date"], new Date());
var user = fetchValue(myObj, [0, "propertyMap", "user"], "");
Just to make sure that we send a default value in case we do not get the desired ojbect. The beauty of this approach is that now you do not have to worry about array or objects nested in the structure. The fetchValue function could be something like below.
function fetchValue(object, propertyChain, defaultValue){
var returnValue;
try{
returnValue = object;
forEach(propertyChain, function(element){
returnValue = returnValue[element];
});
}catch(err){
return defaultValue;
}
if(returnValue == undefined) {
returnValue = defaultValue;
}
return returnValue;
}
Adding the forEach function
function forEach(array, action){
for(var x in array)
action(array[x]);
}

How to parse the first line of the http header?

Is there any javascript function, to parse the first line of the http header?
GET /page/?id=173&sessid=mk9sa774 HTTP/1.1
The url is encoded.
I would like to get an object, like this:
{
"method" : "GET",
"url" : "/page/",
"parameters": {
"id" : 173,
"sessid" : "mk9sa774"
}
}
I searched a lot, but I haven't found anything useful.
thanks in advance,
First you can split on spaces:
var lineParts = line.split(' ');
Now you can get the method, unparsed path, and version:
var method = lineParts[0];
var path = lineParts[1];
var version = lineParts[2];
Then you can split up the path into the query string and non-query string parts:
var queryStringIndex = path.indexOf('?');
var url, queryString;
if(queryStringIndex == -1) {
url = path, queryString = '';
}else{
url = path.substring(0, queryStringIndex);
// I believe that technically the query string includes the '?',
// but that's not important for us.
queryString = path.substring(queryStringIndex + 1);
}
If there is a query string, we can then split it up into key=value strings:
var queryStringParts = [];
if(queryStringIndex != -1) {
queryStringParts = queryString.split('&');
}
Then we can unescape them and stuff them into an object:
var parameters = {};
queryStringParts.forEach(function(part) {
var equalsIndex = part.indexOf('=');
var key, value;
if(equalsIndex == -1) {
key = part, value = "";
}else{
key = part.substring(0, equalsIndex);
value = part.substring(equalsIndex + 1);
}
key = decodeURIComponent(key);
value = decodeURIComponent(value);
parameters[key] = value;
});
If you really wanted to, you could then put all that data into an object:
return {
method: method,
url: url,
version: version,
parameters: parameters
};
If you're in a browser environment, that's the only way to do it. If you're using Node.JS, it can deal with the URL parsing for you.

Categories

Resources