Storing arrays in localstorage - javascript

I'm building an app with Appery.io. It's basically a search app that returns results and then you can click into the results to see details.
Results are returned from a REST api in JSON format, and each results has a number of different items in it, including one that is a JSON array which contains multiple sets of three name/value pairs.
I need the array associated with each result to be available in the details page for that result. I don't want to simply run the search again in the details page, because it is a relatively lengthy process and would slow down the entire app.
I'm aware of using JSON.stringify() to make the array a string, and then storing each array in local storage. However, when I do that in Appery.io, it seems that I either a) just save the first result of the array, or b) am doing it wrong.
Can any provide any insight into how I can go about doing this? Happy to provide code, clarify my question, etc.
Thanks!

If there's some problem using JSON.stringify() with Appery.io, try the approach storing them as comma-separated string (unless you're having commas in values):
> ["foo", "bar"].join();
>> "foo,bar"
And them returning them:
> "foo,bar".split(",");
>> ["foo, "bar"]
Of course, if you're having commas in values, you can use explicitly specified separator for values, like:
> ["foo,bar", "foz,baz"].join("#");
>> "foo,bar#foz,baz"

Related

How can a linq query be converted to JavaScript array containing only values?

I have a JavaScript grid library (it creates a table on the page) that accepts a JavaScript array as input, for rendering in the grid. I'm not certain, however, how to convert a Linq-to-SQL query (against a SQL Server database) to a JavaScript array containing only values.
I tried this, but it included the table column names in the JSON key (and I don't want JSON anyway, I want a JavaScript string array, unless this can be converted to an array?):
JsonConvert.SerializeObject(query)
Example of the format I need to produce:
[1,2,3],[4,5,6]
Environment: .NET Core 3.1
edit: Here is a sample of what I've currently got, this returns the less than desirable JSON (due to the query results being so large, having a JSON key for very element is going to literally double the size of the query):
Devices Table
ID Name
1 iPhone7
2 iPhone8
3 iPhone9
Needed Array (Note: no column names)
[1, "iPhone7"],[2, "iPhone8"],[3, "iPhone9"]
Current C# code in the controller method (returns undesirable key for every element currently)
var query = db.Devices;
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
Technically, you could do this:
var query = db.Devices.AsEnumerable()
.Select(d => new object[]{d.ID, d.Name});
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);
But then the code on the other end of your request is going to have to translate all those arrays back into objects.
It's rarely worthwhile to complicate your model like this in order to optimize the size of your network traffic. If you're pulling enough items over the wire to make this a performance issue, you're likely to encounter a variety of other performance issues. I would first consider other options, like implementing paging.
Did you try
var query = db.Devices.ToList();
var array = JArray.FromObject(query);
return Ok(formattedResult)

Emitted Values Being Sent as One String Instead of Individual Values

In my Angular app I'm returning results via an API call, and allowing users to filter those results through a series of checkbox selections. Right now I'm running into an issue where, while results are returned as expected when one value is sent for a certain filter, when multiple values are selected (like filtering by more than one zipcode, for instance) I get zero results printed to the view. No errors, just no results.
After scratching my head for a while, using Chrome devtools network tab, I finally determined that the problem is that rather than wrapping each item in quotes in the payload - like this: "90001", "90002", what's being sent is this: "90001, 90002". In other words, quotes are wrapped around as if it were one value, not two.
This is the code, where I'm using a "join" to put together the values that are selected:
this.sendZipcode.emit(this.zipcodeFilters.text = arr.length === 0 ? undefined : arr.join(','));
I'm not sure how I can adjust the way this "join" is constructed, or find some other solution instead of "join", in order to have each item wrapped in quotes, rather than wrapped like one long string.
FYI, this is what I see in the network tab of Chrome devtools after selecting two zipcodes. As I explained, it's wrapped like one string, rather than as two values:
addresses.zipCode: {$in: ["90001, 90002"]}
Array.prototype.join will return a string. So you are converting your array to a single string which is being sent as a string. You want to send an array. Simply remove the join call and return arr directly.
String: "value, value"
Array: "value", "value"

Can I configure the default angular filter to display strings so that those that start with the search term come first?

In my project we are displaying a HUGE list of strings (17,000+ sometimes) With an input box for pairing down the list using a filter. I've been using angular's default filter until it was requested that i sort so that strings starting with the search query come before words that merely contain it.
Say i have an array of strings
$scope.array = ["aaa","abb","abc","bad","bcd","cool","cold"]
Right now if i filter with the query string 'c', what will show up is 'abc','bcd,'cool','cold' in that order. However, when most people start searching with 'c' they probably want to see 'cool' and 'cold' show up first. I would like the array to be 'cool','cold','abc',bcd (or possibly cold then cool if alphabetical sorting is part of the package) I'm wary of writing my own filter because I'd rather use something tried and true with such a large collection of data.
Is there a way to achieve this without writing my own custom filter?
It seems like common enough functionality that there should be a config for it or possibly a common filter i can grab from github?
I would think using the angular orderBy with a function that checks if the string starts with C and returns the correct asc value it would do what you need. The question is what would it do after it sorts by the starting characters, does it return the current ordinality of the array, dont know if that even matters for you.
Some pseudo:
$scope.vm.filter = 'c'
$scope.orderByStartsWith = function(item) {
return item.startsWith($scope.vm.filter) ? 0 : 1;
}
<li ng-repeat="item in array | filter:vm.filter | orderBy:orderByStartsWith" >{{item}}</li>
I wish angular would allow you to pass more params into the order by function.

MongoDB shell: printing to console without a trailing newline?

Is there a way to write to STDOUT without a trailing newline from the Mongo shell? I can't seem to find anything other than print() available.
This is related to my SO question on reading a line from the console. Per #Stennie's comment, it is not possible in the current (2.0.6) version of the Mongo shell.
There might be ways to work around it. You can accumulate the results in an intermediate variable (could be an array, string or any other data structure), then print the entire thing in a single line. Below example illustrates use of an array to capture values from query results, then array is converted to string with comma as a separator. In my case I'm interested in just the _id field:
var cursor = db.getCollection('<collection name>').find(<your query goes here>)
let values = []
cursor.forEach((doc) => values.push(doc._id))
print(values.join(','))
Depending on how many results you're expecting, not sure if space consumed by the intermediate data structure might overwhelm memory. If that's the case can craft the query to return smaller, subsets of data that when added together comprise the full result set you're going for.
This is quite old question, however still relevant, so answering.
One can use printjsononeline().

Lucene-like searching through JSON objects in JavaScript

I have a pretty big array of JSON objects (its a music library with properties like artist, album etc, feeding a jqgrid with loadonce=true) and I want to implement lucene-like (google-like) query through whole set - but locally, i.e. in the browser, without communication with web server. Are there any javascript frameworks that will help me?
Go through your records, to create a one time index by combining all search
able fields in a single string field called index.
Store these indexed records in an Array.
Partition the Array on index .. like all a's in one array and so on.
Use the javascript function indexOf() against the index to match the query entered by the user and find records from the partitioned Array.
That was the easy part but, it will support all simple queries in a very efficient manner because the index does not have to be re-created for every query and indexOf operation is very efficient. I have used it for searching up to 2000 records. I used a pre-sorted Array. Actually, that's how Gmail and yahoo mail work. They store your contacts on browser in a pre-sorted array with an index that allows you to see the contact names as you type.
This also gives you a base to build on. Now you can write an advanced query parsing logic on top of it. For example, to support a few simple conditional keywords like - AND OR NOT, will take about 20-30 lines of custom JavaScript code. Or you can find a JS library that will do the parsing for you the way Lucene does.
For a reference implementation of above logic, take a look at how ZmContactList.js sorts and searches the contacts for autocomplete.
You might want to check FullProof, it does exactly that:
https://github.com/reyesr/fullproof
Have you tried CouchDB?
Edit:
How about something along these lines (also see http://jsfiddle.net/7tV3A/1/):
var filtered_collection = [];
var query = 'foo';
$.each(collection, function(i,e){
$.each(e, function(ii, el){
if (el == query) {
filtered_collection.push(e);
}
});
});
The (el == query) part of course could/should be modified to allow more flexible search patterns than exact match.

Categories