$.grep on JSON data in multiple array.fields using wildcards? - dictionary

First off I have looked through similar looking questions but have not found the exact problem asked or answered, so here goes :
I have a JSON Object which consists of about 900+ posts. Looking like this:
var JsonData = [{"rowNumber":563663,"hasWarning":true,"isInvoiceAccount":true,"phone":"","name":"Romerike AS","address1":"Co/Skanning","address2":"PB 52","attention":"","mobile":"","email":"fakt#bos.no","fax":"","zipCity":"N-1471 Askim","invoiceAccount":"","notes":null,"account":"3","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563674,"hasWarning":false,"isInvoiceAccount":true,"phone":"","name":"LILLEHAMMER","address1":"POSTBOKS 110","address2":"","attention":"","mobile":"","email":"","fax":"","zipCity":"N-2605 LILLEHAMMER","invoiceAccount":"","notes":null,"account":"14","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563676,"hasWarning":true,"isInvoiceAccount":true,"phone":"63929788","name":"Askim Bil AS","address1":"Postboks 82","address2":"","attention":"","mobile":"","email":"karosseri#nyg.no","fax":"","zipCity":"N-2051 Askim","invoiceAccount":"","notes":null,"account":"16","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563686,"hasWarning":false,"isInvoiceAccount":true,"phone":"69826060","name":"KAROSSERI A/S","address1":"POSTBOKS 165","address2":"","attention":"","mobile":"","email":"tkar#online.no","fax":"","zipCity":"N-1860 TRØGSTAD","invoiceAccount":"","notes":null,"account":"26","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563690,"hasWarning":false,"isInvoiceAccount":true,"phone":"","name":"AUTOSERVICE A/S","address1":"POSTBOKS 15","address2":"","attention":"","mobile":"","email":"","fax":"","zipCity":"N-2851 LENA","invoiceAccount":"","notes":null,"account":"30","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563691,"hasWarning":false,"isInvoiceAccount":false,"phone":"","name":"ØYHUS A/S","address1":"POSTBOKS 321","address2":"","attention":"John Doe","mobile":"","email":"","fax":"","zipCity":"N-2817 GJØVIK","invoiceAccount":"","notes":null,"account":"31","country":"NORGE","salesRep":"4","countryCode":"no"}];
I want to filter these data before I read them into a table using $.grep.
The JSON data have been loaded as an object.
In the HTML page I have a textfield named "filter".
The following code works, but only when I search for an exact match:
var JsonFiltered = $.grep(JsonData, function (element, index) {
return element.zipCity == $('#filter').val();
});
$.each( JsonFiltered, function ( index, value ) {
// sorting through the array adding values to a table
[...]
});
Problem 1:
I want to use Wildcards when filtering.
I read something about using regexp but I haven't found any viable examples.
Problem 2:
I want to be able to filter more than one column.
Example: filtering the word "Askim" in both element.name and element.zipCity

So I figured out the solutions myself...
Using Wildcards:
var search_term = $('#filter').val();
var search = new RegExp(search_term, "i");
var JsonFiltered = $.grep(JsonTest, function (element, index) {
var zipC = search.test(element.zipCity)
var names = search.test(element.name)
return zipC + names ;
The solution was to use "new RegExp" with the filter "i" setting.
then I took two search.tests combined them in the return command and... presto
Hope this helps anyone else.

Related

How to add any symbols after prefix_?

is there any solution? e.g. I have data in Map with key favorites_ prefix and values _suffix (for example: favorites_jeans, favorites_suit,...,). I want to by dint of loop get that values and set in List, because of it I must give keys of map, right?
I want to know how can I get values of myMap["favorites_*"] (* - after the favorites_ any symbols).
List<String> favoritesStrings = ['favorite_name','favorite_jeans',];
Map<String,dynamic> myMap = {
favoritesStrings[0]:'0',
favoritesStrings[1]:'1',
'someKey':'2',
'anotherKey':'3',
};
favoritesStrings.forEach((favorite)=>print(myMap[favorite]));//prints 0 1
As per what I understood, you want to fetch value from map using "favorites_" + a dynamic value from list as key.
You just have to use String templates and use $ to insert suffix variable to build key dynamically:
List<String> suffixList = ["jeans", "suit", "shirt"];
for(String suffix in suffixList) {
var item = myMap["favorites_$suffix"];
// Do something with item
}
Hope it helps

How to separate multiple columns from a range in an array?

I have a range of data in a Google Sheet and I want to store that data into an array using the app script. At the moment I can bring in the data easily enough and put it into an array with this code:
var sheetData = sheet.getSheetByName('Fruit').getRange('A1:C2').getValues()
However, this puts each row into an array. For example, [[Apple,Red,Round],[Banana,Yellow,Long]].
How can I arrange the array by columns so it would look: [[Apple,Banana],[Red,Yellow],[Round,Long]].
Thanks.
It looks like you have to transpose the array. You can create a function
function transpose(data) {
return (data[0] || []).map (function (col , colIndex) {
return data.map (function (row) {
return row[colIndex];
});
});
}
and then pass the values obtained by .getValues() to that function..
var sheetData = transpose(sheet.getSheetByName('Fruit').getRange('A1:C2').getValues())
and check the log. See if that works for you?
Use the Google Sheets API, which allows you to specify the primary dimension of the response. To do so, first you must enable the API and the advanced service
To acquire values most efficiently, use the spreadsheets.values endpoints, either get or batchGet as appropriate. You are able to supply optional arguments to both calls, and one of which controls the orientation of the response:
const wb = SpreadsheetApp.getActive();
const valService = Sheets.Spreadsheets.Values;
const asColumn2D = { majorDimension: SpreadsheetApp.Dimension.COLUMNS };
const asRow2D = { majorDimension: SpreadsheetApp.Dimension.ROWS }; // this is the default
var sheet = wb.getSheetByName("some name");
var rgPrefix = "'" + sheet.getName() + "'!";
// spreadsheetId, range string, {optional arguments}
var single = valService.get(wb.getId(), rgPrefix + "A1:C30");
var singleAsCols = valService.get(wb.getId(), rgPrefix + "A1:C30", asColumn2D);
// spreadsheetId, {other arguments}
var batchAsCols = valService.batchGet(wb.getId(), {
ranges: [
rgPrefix + "A1:C30",
rgPrefix + "J8",
...
],
majorDimension: SpreadsheetApp.Dimension.COLUMNS
});
console.log({rowResp: single, colResp: singleAsCols, batchResponse: batchAsCols});
The reply will either be a ValueRange (using get) or an object wrapping several ValueRanges (if using batchGet). You can access the data (if any was present) at the ValueRange's values property. Note that trailing blanks are omitted.
You can find more information in the Sheets API documentation, and other relevant Stack Overflow questions such as this one.

Partially update a session variable in meteor?

I think that I might be missing something. I've got the entire contents of a user's product order form stored in a session variable.
var orderFormContents = {
numDoors: 4
numWheels: 4
numSeats: 5
};
Session.set("orderFormContentsSessionVar", orderFormContents);
How do I update the value of just one key in orderFormContentsSessionVar, for instance, just numDoors?
I don't want to overwrite the entire existing contents of the session var.
I would love to be able to do something like:
Session.set("orderFormContentsSessionVar.numDoors", 2);
Something equivalent to _.extend
UPDATE
Following the example of the answer below, I just wrote a function for it:
var updateSession = function(sessionVarName, updateParams){
var obj = Session.get(sessionVarName);
_.extend(obj, updateParams);
Session.set(sessionVarName, obj);
console.log("updated session name: ", sessionVarName, "new session contents: ", Session.get(sessionVarName));
};
Using like you proposed:
var obj = Session.get("orderFormContentSessionVar");
Session.set("orderFormContentsSessionVar", _.extend(obj, {numDoors: 2}));
_.extend should work just fine.
Session.set( "orderFormContentsSessionVar",
_.extend(Session.get("orderFormContentsSessionVar"), { numSeats: 10 }) )
I doubt there is any other way.

JqxWidgets: Export nested grid

While working with JqxWidges I met a problem with exporting nested grids which use one JSON as a source file. The common solution doesn't work. Actually it exports only parent grid colums.
$("#excelExport").click(function () {
$("#jqxGrid").jqxGrid('exportdata', 'csv', chartName + ' ' + date);
});
One of the existing solutions (http://www.jqwidgets.com/community/reply/reply-to-export-data-from-a-nested-grid-13/) propose to push nested rows into data array while calling initrowdetails function.
Yes it works! But only for nested grids and in case when this grid was selected.
So, from this step I am moving to next aproach:
To collect all necessary data into array using initial JSON (prevent you from gathering only separate selected data);
To initialise parent grid columns with all existing data and mark nested columns as hidden. Then when export don't forget to add true parameter to export both non/hidden columns;
Use standard export with custom array parameter;
That's it!
Data collecting:
var toExport = data.allClientsCountChart;
var exp = new Array();
for(var i in toExport){
var client = {};
var countr = toExport[i].countries;
client[labels.clientType]=toExport[i].clientType;
client[labels.clientTypeCount]=toExport[i].clientTypeCount;
exp.push(client);
for(var j in countr) {
var country = {}
var detailes = countr[j].clientDetails;
country[labels.countryType]=countr[j].countryType;
country[labels.clientsNumber]=countr[j].clientsNumber;
exp.push(country);
for(var d in detailes) {
var det = {}
det[labels.scriptName]=detailes[d].scriptName;
det[labels.clientsCount]=detailes[d].clientsCount;
exp.push(det);
}
}
}
Export:
$("#excelExport").click(function () {
$("#jqxGrid").jqxGrid('exportdata', 'csv', chartName + ' ' + date, true, exp, true);
}
And don't forget to set the fifth pafameter into true to export hidden columns.
No doubds, it looks hardcoded. But it works for me.
So, if you have a good solution - please leave a comment!!!

How use a variable name to point different data types with the same name?

I have 2 List one stores the name of filterable columns(of type DropDown) and another store the values to load in those filterable columns.
List<string> filterableFields = new List<string>() { "A_B", "C_D", "E_F" };
List<string> AB, CD , EF;
Now at the run time I get the data from web service and I have written a function to to extract values for these filterable fields and store the values to 2nd List.
private void prepareListForFilterableColumns(XDocument records)
{
foreach (var currentField in filterableFields)
{
var values = (from xml in records.Descendants(z + "row")
let val = (string)xml.Attribute("ows_" + currentField.Replace("_", "_x0020_"))
where val != ""
orderby val
select val
).Distinct();
switch (currentField)
{
case "A_B": AB = values.ToList(); break;
case "C_D": CD = values.ToList(); break;
}
}
}
Now I was thinking that instead of hard coding the assignment in swtich case block, If I could just use the first List name "A_B" and replace "_" from it to point to my 2nd List and assign values.ToList() to it.
I understand that c# is a static language, So not sure if we can achieve this, but IF I can it will make my function generic.
Thanks a lot in advance for time and help.
Vishal
You could use a dictionary of lists of strings instead of 3 lists to store the values.
Dictionary<string, List<string>> val lists = new Dictionary<string,List<string>>();
And make the keys of the dictionary equal to the filterables: "AB", "CD",..
then, instead of AB you would use valLists["AB"] and could then reference reach list based on a string key.
The other option would be to use reflection but that would be slower and unnecessarily a bit more complicated.

Resources