How to compare int as string? - javascript

I'm using Realm in my React Native app.
There is a search bar to filter data by ID, and that ID is int in my database.
If user searches for 418, I need to return all IDs like 41878, 41835.
Here is some code:
findAll({ search }) {
let items = this._realm.objects<Data>(this._schema.name)
if (search.length)
items = items.filtered(`id = '${search}'`)
return items
}
As expected, this code only returns the item that have the exact ID 418.
I tried something like
items.filtered(`id CONTAINS '${search}'`)
But gives me:
Error: Unsupported comparison operator 'contains' against type 'int', right side must be a string or binary type
I can't use Array's filter because it will make the Realm execute the query and slow down the code.
How can I achieve this without triggering the Realm to run the query?

CONTAINS is not supported on Int types.
There are a few solutions:
One is to keep two properties in your model, one an Int and one a String version of that Int. You could implement that pretty easily through an init function within the object that assigns the Int and then makes a string version for the string property
Another is to store all of the values as Strings. You'll just need to Int them if sorting or doing calculations. You can then use CONTAINS

Related

React how to address a key from string name

Ok, so I have a database with data sets in it. the application performs a base API call to retrieve that base data set containing all other data sets. I will receive a string variable with the name of the key I need to access so let's say const addon = "Book". However, I don't know the key name beforehand. So the following code works but I need to somehow not hard code the key parameter but rather use the string value incoming from the const addon. I am not quite sure how to do this please point me to the right documentation or explain how to achieve the wanted result.
const columns = levelOne.Book && Object.keys(levelOne.Book);
However, as the incoming param might not be "Book" but anything else it will only work for this case. It is guaranteed that there is a key-value pair where the key bears the name stored in the string value of addon.
You can use a variable as the key. For example, levelOne[variable] where variable is the string that you want to use as the key.
Also, you can get the keys through Object.keys(levelOne) and then you can set variable value from the keys array.

NewtonSoft JSON converter serializes but does it weirdly. How to fix?

Given the following object
Friend Class GetLocationsResult
Public Property X1 As String
Public Property X2 As String
Public Property X3 As String
Public Property X4 As String
Public Property X5 As String
Public Property X6 As Double
Public Property X7 As Double
End Class
And it is declared and instantiated thusly:
Dim objList as List(of GetLocationsResults) = new List(of GetLocationsResults)
And objList is populated via an iterator that churns through a collection of objects/aggregate classes. The iterator just shoves values into a new GetLocationsResult object and then adds it to the list.
And given the NewtonSoft JSONConvert.SerializeObject(objList) results:
{"d":"[{\"X1\":\"Store Name\",\"X2\":\"Address\",\"X3\":\"City\",\"X4\":\"State\",\"X5\":\"Zip\",\"X6\":Coord1,\"X7\":Coord2}]"}
This point has been addressed and is no longer an issue
There are several issues with this result set. First, for whatever odd
reason, the object being named "d" is not acceptable.
How can I specify something other than "d" for the "name" of the json array?
When I attempt to JSON.parse the response, it needs to be in the following format in order to actually get to the data:
resultSet = JSON.parse(data.d);
console.warn(resultSet[0].X1);
Having to say resultSet[0] is, of course, not acceptable.
How do I cause the 'JSONConvert.Serialize' method to not wrap the response in such a way that I have to refer to the first index of the
resulting JSON data so that I can say resultSet.X1 instead of
resultSet[0].X1?
As requested, here is some more detailed information that may be relevant to the issue at hand.
The data is being returned from a WCF service. The exposed method is decorated thusly:
<WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json)>
and returns type String. The service is being consumed by a desktop application and a mobile platform. The desktop website can have its own method and, in fact, does because we don't want to deal with X1, X2, etc while the mobile platform devs have declared that as necessary. As noted, the method returns a number of results in the form of a custom, aggregate class which is then shoved into a class object which is only a collection of properties. The return statement is thus:
Return JsonConvert.SerializeObject(retVal)
where retVal is a List(of GetLocationsResult)
So while having to access the data via index may be fine for the website, it is not acceptable for the mobile platform. Because each will run their own methods, it is possible to have a unique solution for both if needed.
Three things.
It sounds like you're returning that back through an ASP.NET ASMX
ScriptService or ASPX [WebMethod]. When using one of those
endpoints, you don't need to (and shouldn't) manually serialize the
object into JSON. ASP.NET will do that for you automatically. You don't need to use JSONConvert at all; just return your object as the result. That's why you're seeing all that escaped data after the .d. It's JSON serialized twice.
As WhiteHat mentioned, the .d is a good thing in some situations. It's introduced by default in these ASP.NET JSON services and can't easily be removed on the server-side, but is easy to account for when you parse the response on the client-side.
You are returning a List(of GetLocationResults), which maps to a JavaScript array. That's why you need to use resultSet[0].X1 to access a value in the result. If you want to access that value via resultSet.X1, you need to be sure to return only a single GetLocationResults object instead of a List of them.
Does that help? If you could update your question with a more complete example of your server-side and client-side code, I could give you an example of how to address the preceding three issues.

AngularJS filter orderBy - numbers appear to be considered as string

I have an array of objects which is obtained from JSON in PHP and all properties come back as a string (in quotes) the property required comes back as an int from the API.
I have a particular property let's say 'value' which I convert to integer type (using parseInt()) for each object in the array. I want to apply the orderBy $filter on this property but the order comes back in lexicographical order ( i.e. 9 then 88 then 8... etc) which as far as I'm aware means 'value' is being considered as a string.
The way I apply the filter is as follows:
scope.sortedItems = $filter('orderBy')(scope.sortedItems, sortItems, true);
which uses the function sortItems:
var sortItems = function(item) {
return [item[scope.orderProp], mapping[item.item_rarity]];
};
to apply secondary ordering as well as the primary.
I'm confused as I've also run isNaN on each property everytime the filter is applied and for each object, it comes back as false (is a number). There are some null values but I would assume this doesn't affect anything?
edit: modified the returned JSON to return integers but still no luck.

Filter by column to column sum or operator in BreezeJS

If I have a table with two numeric columns, say X and Y, and need to retrieve rows where say X > Y. How can I achieve this using BreezeJS? All examples I've come across are only capable of comparing columns to a fixed value so far.
Edit:
I tried using .where("Id", "==", "Id") just for testing and got the following error:
Query failed: A binary operator with incompatible types was detected. Found operand types 'Edm.Int32' and 'Edm.String' for operator kind 'Equal'.
To confirm that there were no errors with the query itself I tried .where("Id", "==", 1) and it went through.
Any clue on this anyone?
When Breeze executes a query, it checks the string on the right hand side of the predicate to determine if it is a property name instead of a literal and by default will chose the to treat the value as a property if a property of the same name exists on the type being queried. So if 'qtyOrdered' and 'qtyAvailable' are both properties of the 'Order' type then the following is supported.
var query = EntityQuery.from("Order").where("qtyOrdered", ">", "qtyAvailable");
This behavior can also be overridden ( sometimes necessary for string columns) but is rarely needed.

Safely using eval to use variable as an object name

As shown in this example
javascript-use-variable-as-object-name
I am using eval to use a DOM attribute to select an element from an array. Though there is no direct way for the user to change the input, I want to be as secure as possible and make sure that the variable is indeed an integer before I evaluated it.
Which of the following would be the best, most secure, way?
$(".listitem").click(function(){
var id = $(this).attr("record-id");
if(!isNaN(new Number(id))){
Storage.search.nearby.currec = rowsHolder[eval(id)];
}else{
// send email to admin, shut down
}
});
or
$(".listitem").click(function(){
var id = $(this).attr("record-id");
if(parseInt(id)){
Storage.search.nearby.currec = rowsHolder[eval(id)];
}else{
// send email to admin, shut down
}
});
More, but not required info:
Basically I am pulling down a large JSON string from online, containing an array of records. Upon building a table from the info using a for statement ( for(i in array) ), I push each row into an array called rowsHolder and give the tr an attribute of record-id="i". Then when the user clicks the row, I call the method you see above. I am using PhoneGap with JQuery Mobile.
As always, thanks for the input
-D
There is absolutely no reason to use eval here.
If your id is kind of a number, use parseFloat(id) to get it. Unnecessary as it would be converted back to a string when used as a property name, though.
If your id is an integer, use parseInt(id, 10) to get it. Unnecessary as it would be converted back to a string when used as a property name, though.
If your id is a string, just let it be a string. The property name you use it for would be one anyway.

Categories

Resources