Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter inner arrays from multi-dimensional array

I am trying to pull out variables (safety_rating_id, score etc.) from an array (called array) based on the submission_id using the swift library Dollar (https://github.com/ankurp/Dollar)'s find method so that I can later make a POST request (Eventually, I hope to be able to replace the hardcoded values in my parameter with the pulled array variables) with them but my results from find all return nil.

These are the inner arrays I want where the submission_id is 27 from this array https://codeshare.io/zr1pw (lines 22- 36):

{
 "submission_id" : "27",
 "name" : "Equipment",
 "task_id" : "37",
 "points" : "10",
 "safety_rating_id" : 105,
 "score" : "9"
}, {
 "submission_id" : "27",
 "name" : "Emergency Equipment",
 "task_id" : "37",
 "points" : "10",
 "safety_rating_id" : 106,
"score" : "9"
}

Code:

  var array: [JSON] = []   
  func submitScore(onCompletion: () -> (), onError: ((NSError) -> ())? = nil) {

    guard let endPoint = Data.sharedInstance.submitScoreEndpoint
        else { print("Empty endpoint"); return }

    let user = Users()

    let test = $.find(self.array, callback: { $0 == 27 })
    print(test)

    let Auth_header = [
        "Authorization" : user.token,
        ]

    let parameters: [String:Array<[String:Int]>] = [
        "ratings" : [
            [
                "safety_rating_id" : 105,
                "schedule_job_id" : 18,
                "score" : 9,
                "submission_id" : 27
            ],
            [
                "safety_rating_id" : 106,
                "schedule_job_id" : 18,
                "score" : 10,
                "submission_id" : 27
            ]
        ]
    ]


Alamofire.request(.POST, endPoint, headers: Auth_header, parameters: parameters, encoding: .JSON)
        .validate()
        .responseJSON {
        response in

        switch response.result {
        case .Success(let data):
            let json = JSON(data)
            print(json)
            onCompletion()
        case .Failure(let error):
            print("Request failed with error: \(error)")
            onError?(error)
        }

    }

}

UPDATE

I'm able to obtain the array with submission_id 27 BUT I want to remove name and task_id from the two submission_id : 27 arrays AND add an schedule_job_id that I got from elsewhere.

I've tried using a for in loop to create my own array from the variables that I want but I keep getting a nil crash. This is what the new array looks like https://codeshare.io/3VJSo

for in loop error

Eventually I want to do a "ratings" : [chosenArray]

like image 896
noobdev Avatar asked May 31 '16 03:05

noobdev


People also ask

How to create a multidimensional array in Python?

In Python, Multidimensional Array can be implemented by fitting in a list function inside another list function, which is basically a nesting operation for the list function. Here, a list can have a number of values of any data type that are segregated by a delimiter like a comma. Nesting the list can result in creating a combination ...

How to filter ndarray with filter in NumPy?

If arr is a subclass of ndarray, a base class ndarray is returned. Here, we first create a numpy array and a filter with its values to be filtered. To filter we used this fltr in numpy.in1d () method and stored as its values in the original array that return True if condition fulfills.

How do you filter an array of objects with 3 fields?

If your object contains 3 fields, say email, firstName, lastName then you use this. ArrayObject .filter (em => em.email.indexOf (searchEmail) > -1) .filter (fn => fn.firstName.indexOf (searchFirstName) > -1) .filter (ln => ln.lastName.indexOf (searchLastName) > -1)

How to select an element from a multidimensional array?

PHP - Multidimensional Arrays 1 For a two-dimensional array you need two indices to select an element 2 For a three-dimensional array you need three indices to select an element More ...


2 Answers

So what gets passed inside of the callback is each element in the array so you will get passed the dictionary object. So if you want to find a specific item in the array you should do

let test = $.find(array) { $0["submission_id"]! == "27" }

If you want all elements in array that have submission id as 27 then use filter

let test = array.filter { $0["submission_id"]! == "27" }

To remove properties from a dictionary object you need to call removeValueForKey method on each item on the array.

let jsonWithMySubmissionId = self.array.filter ({ $0["submission_id"]! == 27 })
for json in jsonWithMySubmissionId {
  json.removeValueForKey("name")
  json.removeValueForKey("task_id")
  ...
}
like image 154
Encore PTL Avatar answered Nov 14 '22 23:11

Encore PTL


Your dic in your for loop must be type of NSMutableDictionary. Because you can't manipulate NSDictionary.

Second thing there is no method like removeValueForKey.

You should use removeObjectForKey or removeObjectsForKeys.

In removeObjectsForKeys you have to pass array of parameters (keys as parameter).

In removeObjectForKey you can pass one string (key) as parameter.

like image 24
Ketan Parmar Avatar answered Nov 14 '22 22:11

Ketan Parmar