select in a parsed json, comparing id with an array of ids - ruby-on-rails

i need to filter array result (get by parsed json).
if i know the exact id i can select in the json using
#my_art = ele_art.select { |articolo| articolo['id'] == 456 }
Now I have an array of ids called #myarray and i need to select in ele_art only the items with id in the array
Reading the array i have:
[279, 276]
i tried with
#my_art = ele_art.select { |articolo| articolo['id'] == #myarray }
or
#my_art = ele_art.select { |articolo| articolo['id'] in #myarray }
with no luck!
how can i solve?

#my_array is and array of ids, so, in that case you need to check if articolo['id'] is included in #myarray. For those cases, the Array class in Ruby has the include? method, which receives an object and returns true/false if the object is included or not in the array.
So, in your case try something like:
#my_art = ele_art.select { |articolo| #myarray.include?(articolo['id']) }

Related

fill dictionary values in loop

I have a dictionary var items = [String:String]()
Then I assign values :
for i in itemInCart {
items["param_id"] = i.modelId
//items["param_id"]?.append(i.modelId!)
}
print(items)
I have just a last value.
I know that the method append() is not applicable to dictionaries, but how can I fill it then?
This is because you are replacing param_id every time for loop i so it will always a last element you will found
You have two options, either create a unique key for each element (a bad idea) or if you want all the elements you have to create array and add it into the param_id key like:
items["param_id"] = itemInCart.map { $0.modelId }
so now your dictionary is [String:Any]() or [String:[String]]()

Group TableView items from NSArray returned in JSON Response in Swift

I have a table view and I want to populate the table view with the values provided to me in a JSON response in the form of NSArray and I have used the code below to extract this NSArray:
dispatch_async(dispatch_get_main_queue(), {
print(json)
if let listDictionary = parseJSON["list"] as? NSArray {
print("LIST: \(listDictionary)")
}
})
In JSON response, I get the following array of two elements as shown below:
list = (
{
"is_cover" = 0;
"is_recommand" = 0;
name = "Helena's Signature Dish";
ord = 5;
price = "105.00";
remark = "Helena's special made dish is one of the most priced and delicious dishes in the whole world.";
thumb = "56c351887a0e0.jpg";
},
{
"is_cover" = 0;
"is_recommand" = 0;
name = "Pineapple Fried Rice";
ord = 6;
price = "110.00";
remark = "We have the most delicious pineapple rice in the whole world!";
thumb = "56c704e15da79.jpg";
}
);
Now I want to show the value "name", "price" and "remark" fields from each element in the array into a UITableView.
But I can't find a way to break the values for name, price and remark for each element and put them into an another array so they can be displayed in a table view somehow because each element contains a very long string and I only need to extract some values from this string. Can anyone please help me with this as I'm very new to Swift.
Thanks!
You don't need to make a second array, Only extarct particular json from array in cellForRowatIndexPath on dictinary by objectatindex method of array and now you can access.
You can achieve it by creating a model Class which contains only
those properties which you needed.
Once you get the response array from server , iterate though each
dictionary and create a Model Object.Add this model objects in the
Array.
Use this model object in the Array for applying data in your cell using the index
One more thing to add is always prefer using objects as it gives (.)dot syntax & autosuggestion, so there will be less chances of
making mistakes. As if you use Dictionary there will be more chances
of using incorrect key getting crash
I fixed this by putting values in "name", "price" and "remark" fields into another array using flatMap as shown below:
let nameArray = listArray.flatMap({ element in (element["name"] as? String)! })
And then I got something like:
Name's: (
"Helena's Special Dish",
"Pineapple Fried Rice"
)
and then in the tableView function for cellForRowAtIndexPath I grouped the values in tableview.

Access Parse Array Elements

I have an array column in Parse that is called homeAddress. Inside it is the following value for a single row:
["111111","222222"]
I wish to access this in swift. I created a local array called homeAddress of String type. How can I store the first element in the Parse column (i.e. 111111) in the first element holder in local array i.e. homeAddress[0]? And then I need to store the 222222 in the homeAddress[1].
So what you want is load this data from parse. You can just call a Parse Query get the results and work with them:
let query = PFQuery(className:"ClassName")
query.findObjectsInBackgroundWithBlock {
(results, error) -> Void in
if (error == nil) {
for object in results!{
let homeAddress = object["homeAddress"] as! NSArray
}
}else {
print(error?.userInfo)
}
}
One way would be to trim first and last character and just separate values by comma:
var test = "[\("111111"),\("222222")]"
var trimmedStringRange = Range<String.Index>(start: test.startIndex.successor(), end: test.endIndex.predecessor())
var homeAddress = test.substringWithRange(trimmedStringRange).componentsSeparatedByString(",")
If your local array is empty, you can add your values from the parse array like this (after getting the array from Parse):
localHomeAddress.append(homeAddress)
This will put all values from homeAddress array in localHomeAddress array.
If you use a splice, you can ensure you are adding the values from index 0:
localHomeAddress.insertContentsOf(homeAddress, at:0)

Retrieving an array from a multidimensional array

My response from an API is coming in like:
[0] = "[Identity[id=95571, type=start, userId=d12345, processId=95567]]"
[1] = "[Identity[id=95572, type=start, userId=d67890, processId=95568]]"
etc
Lets call the above arr.
I want to retrieve all the userIds
I have tried:
all_users = arr.collect {|ind| ind[2]}
But this is obviously incorrect. What am I missing?
Thanks
Your array elements are strings, so can use string methods to extract parts from them, e.g.
arr.map { |e| e.match(/\[id=(/d+),/)[1] }

ios swift parse: get data out of parse and use them

I find only in the docs how the query can look like to select data.
As far as I see, there is only one way to collect 1 or many results:
var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
// The find succeeded.
NSLog("Successfully retrieved \(objects.count) scores.")
// Do something with the found objects
for object in objects {
NSLog("%#", object.objectId)
}
} else {
// Log details of the failure
NSLog("Error: %# %#", error, error.userInfo!)
}
}
What I cant figure out (as I am a beginner!) is how to access the object data. Lets say I have the fields "name", how can I get it? What is the right syntax? Especially if I have more than 1 result?
For just one result I would do:
var name = object["name"] as String
myArray.append(name)
Even that can't be right? To use "var xx = xx" within the loop?
And what do I do when I have more than one result?
Other thought:
Declaring the var name: String! before I do the query and then:
name = object["name"] as String
self.myArray.append(name)
Returns the error: Immutable vaue of type [String] only has mutating members named 'append'
What would be the correct way to "work" with the data the query returns?
Another question: as those querys are async, they finished later and the method is "done" much more earlier, this way my array with names is empty when the view is shown and I receive the data at a later stage. What is the best practice here to have all data available before the view is delivered to the device?
Thanks so much!!
You can use objectForKey on your object. So instead of using var name = object["name"] as String you can use:
for object in objects {
var name = object.valueForKey("name") as String
}
But the other parts are absolutely fine. You can create an array somewhere in you code and then add the objects to it. to do that, you can loop through your objects and than add the objects to your array. Like that:
if error == nil {
// The find succeeded.
NSLog("Successfully retrieved \(objects.count) scores.")
// Do something with the found objects
for object in objects {
var name = object["name"] as String
myArray.append(name)
}
}
Because you can reuse the var name because every loop-element will be filled into the variable name and will erase the last value. But the array will get the new value appended. For example:
First loop. The value at the first index of your objects gets loaded into the object. For example with the value "John".
variable name's value is now the value of the object["name"] of the current loop. So name has the value John
Now you add the value to your array.
The second loop starts and the second element gets loaded inside object which now has the string Michael.
The Variable name's new value is now the value of object. So name's value is now Michael
and so on.

Resources