Swift 3 - Get value from array of dictionaries - arrays

Trying to get the value and the key of a dictionary that's stored in an array to populate two UILabels.
My array looks as follows:
var fromLocations = [["marco" : "polo"],["jekyll" : "hide"],["freddy" : "jason"]]
I'm getting the index by a collection view's indexPath. Currently trying the following:
cell.locationName.text = fromLocations[indexPath.item].values[1]
I've tried a bunch of other ways but I can't nail it.

Is this what you are trying to do?
var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]]
let marco = fromLocations[0]["marco"]
print("marco = \(marco)")
This prints "polo1". Basically you are accessing the first item of the array which is a dictionary. You then access that dictionary the way you would normally access a dictionary.
So a break down would be:
let fromLocations = [["marco" : "polo"],["marco" : "polo"],["marco" : "polo"]]
let theDictionary = fromLocations[0]
let value = theDictionary["marco"]
To just get the values as an array with using the key (which is strange), turn the values into an array.
var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]]
let marco = Array(fromLocations[0].values)[0]
print("marco = \(marco)")
This will print "polo1"

Related

How to push object into an array? in Angular 7

I am pushing an object into an array but cannot do it?
I'm doing it like this
this.passData = this.tribeForm.value;
var id = {"tribe_id": 1}
this.passData.push(id)
This is the value in the tribeForm
I also tried
var id = {tribe_id: 1}
and
this.passData.splice(0,0, id)
and
this.passData = Array.prototype.slice(id)
and
this.passData.concat(id)
but it all ends up with
TypeError: this.passData.push/splice/concat is not a function
The question is not that clear, But I understood you are manipulating form data, value of form data returns an Object, Not an array. Objects in JavaScript are represented as key-value pairs, (or attribute-value) pairs.
Example :
var object = {
name : "Jhon",
grade : 12,
gpa : 8.12
}
It is just a collection of key-value pairs, push(), concat() and other methods are supported only for Arrays not for Objects. You can achieve whatever you want simply by creating a new key/attribute and assigning the value to it.
this.passData = this.tribeForm.value
this.passData['tribe_id'] = 1
//or, Objects can also contain nested object
this.passData['someKey'] = {'tribe_id' : 1}
You can create an empty array and push objects to it
Example :
var exampleArray = []
exampleArray.push({'tribe_id' : 1})
Now, it works because exampleArray is an Array not JS object.
Thanks for A2A
First, you need to understand the error:
TypeError: this.passData.push/splice/concat is not a function
Push/splice/concat is functions for Array and because of that the console is yelling at you that the passData is not an Array.
Make sure your passData is an Array and you will able to do so.

Swift 3: Dictionary from large arrays

I am working with two large arrays containing following data:
print(dataID[1]) // ["DataID123"]
print(dataAR[1]) // ["73.075584"]
I'd like to form a dictionary from the two arrays by:
var arrayofDict = [String: AnyObject?]()
for i in 0...csvDataID.count {
if i < csvDataID.count {
let key = csvDataID[i]
let value = csvDataAG[i]
arrayofDict[key] = value
}
}
But get following error:
Cannot subscript a value to '[String: AnyObject?]' with an index of
type '[String]'
I also tried a few other approaches aswell resulting in the same error.
Could anyone help me and is there even a more efficient way to handle the arrays?
Thanks!
let key = csvDataID[i][0]
let value = csvDataAG[i][0]
Explaination:
The log says that csvDataID[1] is an array: ["DataID123"]
The same is for the second one.:["73.075584"]
So,
let key = csvDataID[i] // you set the key is array.
That's why you can see this error.

swift - using .map on struct array

i have a struct array that i want "break up" into smaller arrays that can be called as needed or at least figure out how i can map the items needed off one text value.
the struct:
struct CollectionStruct {
var name : String
var description : String
var title : String
var image : PFFile
var id: String
}
and the array made from the struct
var collectionArray = [CollectionStruct]()
var i = 0
for item in collectionArray {
print(collectionArray[i].name)
i += 1
}
printing partArray[i].name gives the following result:
pk00_pt01
pk00_pt02
pk00_pt03
pk01_pt01
pk01_pt02
pk01_pt03
pk01_pt04
pk01_pt05
pk01_pt06
pk01_pt07
pk01_pt08
this is just some test values but there could be thousands of entries here so i wanted to filter the entire array just by the first 4 characters of [i].name i can achieve this by looping through as above but is this achievable using something like .map?
I wanted to filter the entire array just by the first 4 characters of
[i].name
You can achieve this by filtering the array based on the substring value of the name, as follows:
let filteredArray = collectionArray.filter {
$0.name.substring(to: $0.name.index($0.name.startIndex, offsetBy: 4)).lowercased() == "pk00"
// or instead of "pk00", add the first 4 characters you want to compare
}
filteredArray will be filled based on what is the compared string.
Hope this helped.
If you want to group all data automatically by their name prefix. You could use a reducer to generate a dictionary of grouped items. Something like this:
let groupedData = array.reduce([String: [String]]()) { (dictionary, myStruct) in
let grouper = myStruct.name.substring(to: myStruct.name.index(myStruct.name.startIndex, offsetBy: 4))
var newDictionart = dictionary
if let collectionStructs = newDictionart[grouper] {
newDictionart[grouper] = collectionStructs + [myStruct.name]
} else {
newDictionart[grouper] = [myStruct.name]
}
return newDictionart
}
This will produce a dictionary like this:
[
"pk00": ["pk00_pt01", "pk00_pt02", "pk00_pt03"],
"pk01": ["pk01_pt01", "pk01_pt02", "pk01_pt03", "pk01_pt04", "pk01_pt05", "pk01_pt06", "pk01_pt07"],
"pk02": ["pk02_pt08"]
]
Not sure if i am understanding you correctly but it sounds like you are looking for this...
To create a new array named partArray from an already existing array named collectionArray (that is of type CollectionStruct) you would do...
var partArray = collectionArray.map{$0.name}

Is it possible to access a String inside an Array, inside an Array in swift?

Is it possible to access a string inside an array that is inside another array? - Swift
for instance:
var a = 1
var b = 2
var maleDogs = ["Fido","Thor"]
var femaleDogs = ["Linn","Eva"]
var dogs = [maleDogs,femaleDogs]
And then do something like
dogs[a][b]
In this instance, I wanted to get "Thor" as an output, but it calls an error. (Inside playground)
Your code is completely correct, but note that Swift array indices are zero-based, so accessing index 2 causes an "Array index out of range" exception.
You can see the error message if you open the "Assistant Editor" for the Playground file
(View -> Assistant Editor -> Show Assistant Editor).
What you probably wanted is
var a = 0
var b = 1
var maleDogs = ["Fido","Thor"]
var femaleDogs = ["Linn","Eva"]
var dogs = [maleDogs,femaleDogs]
dogs[a][b] // Thor

Sorting an arraycollection with a numeric value coming from 2 diffrent fields

Hi guys I need to sort an arraycollection. the problem is that my array is combined from two diffrent arrays, in one the age field is called "AGE", and in the other the age is called "MYAGE".
Now I need to sort the combined array according to age but I got two fields with diffrent names. I can go through the array and change all "MYAGE" to "AGE" but i was wondering if theres maybe a way to sort the array in its current status?
Thanks ahead
Say you have an ArrayCollection called myCollection. I hope the following will solve your request for that:
private function compareItems(a:Object, b:Object, fields:Array = null):int
{
var firstValue:Number = "AGE" in a ? a["AGE"] : a["MYAGE"];
var secondValue:Number = "AGE" in b ? b["AGE"] : b["MYAGE"];
if (firstValue == secondValue)
return 0;
return firstValue > secondValue ? 1 : -1;
}
…
var sort:ISort = new Sort();
sort.compareFunction = compareItems;
myCollection.sort = sort;
myCollection.refresh();

Resources