Can I convert a JSON string to a Flex ArrayCollection in without changing the item order? - string

Regarding this issue, I have generated dynamically string from Java .each time string format change , for example String format is
[{"BranchName":"Corporate Office","Date":"08\/03\/2013","SPName":"Pharmacy","SPAmount_5-00%":"100.00","SPVATAmount_5-00%":"15.00","SPOtherCharges_5-00%":"30.00","SPAmount_14-50%":"200.00","SPVATAmount_14-50%":"39.00","SPOtherCharges_14-50%":"71.00","SPColTPA":"100.00","SPColChequeDD":"50.00","SPHdfcCC":"100.00","SPIdbiCC":"100.00","SPColCash":"50.00","Difference":"55.00"},
But when I convert array collection with following code .
var rawData:String = String(event.result);
var arr:Array = (JSON.decode(rawData) as Array);
var dp:ArrayCollection = new ArrayCollection(arr);
but array collection order changed as default sort like [Branch, Date, Difference,.. ] . But I want same as string format order. So How can I prevent Default order.

Actually, what you've described here is an array of objects (your example just includes one object). In the JSON parsing to array, each object is indeed in the order in which it is declared; but in the OBJECTS that are created, the properties may not be listed in the same order.
For example:
'[ {"Branch":"Corporate", "Department":"Finance", "Cost":"10000", "Attended":"true"},' +
'{"Branch":"Las Vegas", "Department":"Hospitality", "Cost":"20100", "Attended":"false"},' +
'{"Branch":"San Diego", "Department":"Banking", "Cost":"11023", "Attended":"true"}]'
Parsing would return arr[0] as the Corporate object, arr[1] as the Las Vegas object, etc. Iterating through the properties I got:
var obj:Object = dp.getItemAt(0);
for (var prop:String in obj) {
trace(prop + ' is ' + obj[prop]);
}
Department is Finance
Attended is true
Branch is Corporate
Cost is 10000

Related

NODE.JS: iterating over an array of objects, creating a new key if it does not exist

I am iterating over a collection of data, in my case, an array of objects. Here is a sample of 2 data points from it:
{
violation_id: '211315',
inspection_id: '268804',
violation_category: 'Garbage and Refuse',
violation_date: '2012-03-22 0:00',
violation_date_closed: '',
violation_type: 'Refuse Accumulation' },
{
violation_id: '214351',
inspection_id: '273183',
violation_category: 'Building Conditions',
violation_date: '2012-05-01 0:00',
violation_date_closed: '2012-04-17 0:00',
violation_type: 'Mold or Mildew' }
I need to create a new array of objects from this, one for each "violation_category" property. If Violation category already exists in the new array I am creating, i simply add the information to that existing category object (instead of having two "building conditions" objects for example, I would just add to an existing one).
However, I am having trouble assigning to the existing object if the current one exists (it's easy to check if it does not, but not the other way around). This is what am attempting to do currently:
if (violationCategory.uniqueCategoryName) {
violationCategory.uniqueCategoryName.violations = results[i].violation_id;
violationCategory.uniqueCategoryName.date = results[i].violation_date;
violationCategory.uniqueCategoryName.closed =
results[i].violation_date_closed;
} else {
category.violations = results[i].violation_id;
category.date = results[i].violation_date;
category.closed = results[i].violation_date_closed;
violationCategory.push(category);
}
In first condition, if this category (key) exists, I simply add to it, and in the second condition, this is where I am struggling. Any help appreciated. Thanks guys.
Just add an empty object to the key if there no object there :
violationCategory.uniqueCategoryName = violationCategory.uniqueCategoryName || {};
And only then, add the data you want to the object.
violationCategory.uniqueCategoryName.violations = results[i].violation_id;
violationCategory.uniqueCategoryName.date = results[i].violation_date;
violationCategory.uniqueCategoryName.closed =
results[i].violation_date_closed;
No condition needed.
Good luck!
Assuming that you have an input variable which is an array of objects, where the objects are looking like the objects of the question, you can generate your output like this:
var output = {};
for (var item of input) {
if (!output[item.violation_category]) output[item.violation_category] = [];
output[item.violation_category].push(item);
}
Of course you might customize it like you want.

Map to hold multiple sets of key and values

I have a map1 which holds the information as
[40256942,6] [60246792,5]
Now that I want to prepare a map2 that holds information such as
itemNo, 40256942
qty, 6
itemNo, 60246792
qty, 5
to prepare final information as json
“partialArticlesInfo”: [{itemNo:”40256942”, availQty:”6”}, {itemNo:”60246792”, availQty:”5”}]
I am trying to iterate map1 to retrieve values and set that against the key. But I am getting only one entry which is last one. Is there any way , I get the new map with entries such as mentioned above
Map<String, String> partialArticlesInfo = new HashMap<String,String>();
Map<String, String> partialArticlesTempMap = null;
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet())
{
partialArticlesTempMap = new HashMap<String,String>();
partialArticlesTempMap.put("itemNo",entry.getKey());
partialArticlesTempMap.put("availQty",entry.getValue());
partialArticlesInfo.putAll(partialArticlesTempMap);
}
In Java (I'm assuming you're using Java, in the future it would be helpful to specify that) and every other language I know of, a map holds mappings between keys and values. Only one mapping is allowed per key. In your "map2", the keys are "itemNo" and "availQty". So what is happening is that your for loop sets the values for the first entry, and then is overwriting them with the data from the second entry, which is why that is the only one you see. Look at Java - Map and Map - Java 8 for more info.
I don't understand why you are trying to put the data into a map, you could just put it straight into JSON with something like this:
JSONArray partialArticlesInfo = new JSONArray();
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet()) {
JSONObject stockEntry = new JSONObject();
stockEntry.put("itemNo", entry.getKey());
stockEntry.put("availQty", entry.getValue());
partialArticlesInfo.put(stockEntry);
}
JSONObject root = new JSONObject();
root.put("partialArticlesInfo",partialArticlesInfo);
This will take "map1" (partialStockArticlesQtyMap in your code) and create a JSON object exactly like your example - no need to have map2 as an intermediate step. It loops over each entry in map1, creates a JSON object representing it and adds it to a JSON array, which is finally added to a root JSON object as "partialArticlesInfo".
The exact code may be slightly different depending on which JSON library you are using - check the docs for the specifics.
I agree with Brendan. Another solution would be otherwise to store in the Set or List objects like the following.
class Item {
Long itemNo;
int quantity;
public int hashCode() {
Long.hashCode(itemNo) + Integer.hashCode(quantity);
}
public int equals(Object other) {
other instanceOf Item && other.itemNo == this.itemNo && other.quantity = this.quantity;
}
}
}
then you can use the JsonArray method described by him to get the Json string in output
This means that adding new variables to the object won't require any more effort to generate the Json

How to access individual values from an NSArray?

Trying to iterate through an array of values coming in from a push notification.
This is what the object in push notification object would look like:
"storyids": [12345, 12346, 12347, 12348]
At which, I can intercept this value in my ios app delegate, as such:
storyIds = aps.ObjectForKey(new NSString("storyids")) as NSArray;
But now I am having trouble iterating through this collection (which I want to essentially convert to a C# collection)
This is what I've tried:
for (nuint i = 0; i < storyIds.Count; i++)
{
var j = storyIds.ValueAt(i);
}
Which gives me a weird number and not the value at that particular index. I can't seem to find any method of NSArray to get the value from the array at a particular index.
You could use storyIds.GetItem<NSString> (0) or NSString.FromHandle (storyIds.ValueAt (0)).

Checking what a value is in SSJS

I have this block of code in SSJS that I'm doing some field validation stuff:
thisDoc is a NoteXspDocument
fld = the name of a field
var thisValue = thisDoc.getValue(fld);
print("Check Text = " + thisValue);
print("Is is a Date " + (thisValue === Date))
when I run it the log has this:
Check Text = 09/10/15 12:00 PM
Is is a Date false
In this code I do not know what the datatype is of the fld which is a field name. I check the backend document and get the NotesItem.Type() and this field is of type text 1280 in the backend, but the NotesXspDocument has a date. I need to determine what the data type is thisValue sure acts like a NotesDateTime object, but I'm doing something wrong somewhere.
I think the issue might be the difference between a NotesDateTime and a java.util.Date but they drive me up the wall.
Further Edit --
The problem is that I have an Array of field names var Fields:Array that I then loop through and get fld = Fields[n] so when I get the value of the field it could be anything Text, Date, Number so when I do var thisValue = thisDoc.getValue(fld) or thisDoc.getItemValue(fld) I need to figure out what kind of value I have. I guess I could put the getItem..... inside a try until I find one that works but that seems like a less than optimum solution.
Try instanceof Date.class. What you've got is not checking the data type of thisValue against the underlying class, instead it's checking the object itself.
Because the field that I am retrieving can be just about anything I use
var thisValue = thisdoc.getValue(fld);
i had a lot of trouble then determining what kind of data I had. It could be a null Date/Number/String So the first thing I did was find out what the backend data type was:
var thisItem:NotesItem = thisDoc.getDocument().getFirstItem(fld);
var type:Integer = thisItem.getType()
This helps somewhat if the field has been previously set, but if it is a new document or the field has not received a value yet it will be type 1280 or text and probably null.
So my fisrt test is for null or "". then it becomes a bit tougher because I need to test for some values. In all my comboboxs I add the text "--- Select ?????" as the first item in the list so I tried to get a substring of "---" but because of variance in the datatype I needed to put that in a try:
try{
if (thisValue.substring(0,3) == "---"){
print("have null Prefix");
rtn = false;
errMsg.push("The field " + fld + " is a Required Field please enter a value");
break;
}catch(e){ etc
I then wrapped the various other datatype tests in trys and now I have it working.
Might be a better way but this works.
Use .getItemValue() to return a vector array, then test the data type. You can also try .getItemValueString() to return a text string or .getItemValueDate() or .getItemValueDateTime() to return date/time.
Since getItemValue() returns an array, use subscript to get the first element:
var thisValue = thisDoc.getItemValue(fld);
var thisIsDate = (thisValue[0] instanceof Date);
print("Check Text = " + thisValue[0]);
print("Is this a Date ? " + thisIsDate;

How to search and sort in J2me (ascending or descending)

I am wondering about how to search in J2ME. I have been searching in the internet, so many result show to me, and I see in Java2s.com I got a result use RecordFilter and matches method for search in record store.
But my problem is, when I need to pass 2 or more parameters into it. How can result matches with these parameter?
And how to sort descending or ascending like bubble sort?
Concatenate your searches into a single String variable. Separate each of them with ; for example. In the code of the matches method explode the String to get each search criteria.
To make the filter in effect create an instance of SearchFilter and call the matches method with the concantenated String as its param.
For the sort implement the RecordComparator interface ; implement the compare method to build your sort criteria. Make a google search about j2me+recordcomparator to see examples about how to make sorts.
EDIT :
In the code of the matches method explode the String param obtained from the byte[] param. Treat each String exploded to make the criteria.
As I understand you want to pass two string as a search criteria when you wrote :
SearchFilter search = new SearchFilter(txtSearch.getString(), strType);
So in the constructor there should be two params !!!
When you want to make the matching then call
if searchFilter.matches((search1+";"+sType).getBytes())
Then explode the candidate param into two String when you code the matches method.
When I save my Data in RMS I save it as a String[] like I want to save Name, Age,Salary,EmpID for each employee I save it create an array and convert it to bytes and save it in RMS. When i retrieve it i do the reverse process. Now if i want to get employee with names starting with A and with salary 10000 i use the following filter
class UtilFilter implements RecordFilter{
public UtilFilter(String str_searchText,String str_searchText1)
{
this.str_searchText = str_searchText.toLowerCase();
this.str_searchText1 = str_searchText1.toLowerCase();
}
public boolean matches(byte[] bt_byteData)
{
String str_str = "";
String str_str1 = "";
//here goes code how u get back ur String[] from RMS say u get it in Data
str_str = Data[0].trim();
str_str1 = gd_cd.Data[2].trim();
if(str_searchText != null && str_searchText1 != null && str_str.equals(str_searchText) && str_str1.equals(str_searchText1 ))
{
return true;
}
else
{
return false;
}
}
}
This way i can filter any no of parameters.Hope tht helps! :)

Resources