I have a form that creates a array with data, then i place that array in a object in my firebase Datatime.
When i get the data from that object, the data in object with 2 arrays.
The problem is to use *ngfor i need the object to be an array with arrays in it. Is it possible?
How can i make it?
The object:
{adeus: Array(1), olaaaaa: Array(2)}
how i call it from firebase:
listSearch(){
this.af.object("/list").query.once('value').then(data => {
console.log(data.val() as string);
this.teamsList = data.val() as string;
});
}
I get this error:
core.js:4197 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays
So i need a way to convert that object to an array with two arrays.
Any help?
I not understand the solution that you want to made. But if you want to iterate into the properties of an object you can use Object.keys as follow
let object = { array1 : ['a','b'], array2 : ['c','d'] }
let arrayOfArrays = Object.keys(object).map(k => object[k])
the result will be
arrayOfArrays = [ ['a', 'b'], ['c', 'd'] ]
Hope this can help you
Related
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.
I'm developing an iOS app and I want to access a specific value in a Dictionary using Array().
My dictionary contains an array, which contains structs.
let array = [(key: "S", value: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))]), (key: "T", value: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))])]
I'm making an UITableView with the array: the section name is the key value, the cell title is the repoStruct.repoName value, and the same with the following values.
To access repoName I'd use Array(array)[0].1[0].repoName.
The problem is that I do not know the exact location I want to access, instead, I use indexPath to know which value I need:
Array(array)[indexPath.section].indexPath.row[0].repoName
This should return me the repoName of the cell, but instead gives me the following error: Value of tuple type '(key: String, value: [repoStruct])' has no member 'indexPath'
I also tried using:
let row = indexPath.row
Array(array)[indexPath.section].row[0].repoName
but it gives me the same error: Value of tuple type '(key: String, value: [repoStruct])' has no member 'row'
I do not know why Array(array)[0].1 works and returns me the value, but Array(array)[indexPath.section].row doesn't. It is doing the same: accessing a value using the position, which is an int, such as indexPath.
How could I accomplish this?
Thanks in advance.
You are strongly discouraged from using tuples in a data source array. Replace the tuple with an extra struct
struct Section {
let name : String
let items : [Thunderbolt.repoStruct]
}
let array = [Section(name: "S", items: [Thunderbolt.repoStruct(repoName: "Semiak Repo", repoURL: "https://repo.semiak.dev", icon: Optional("iconRound"))],
Section(name: "T", items: [Thunderbolt.repoStruct(repoName: "Thunderbolt iOS Utilities", repoURL: "https://repo.thunderbolt.semiak.dev", icon: Optional("iconRound"))]]
and get an item at index path
let section = array[indexPath.section]
let item = section.items[indexPath.row]
let name = item.repoName
First of all, your array is already an array, so there's no need to say Array(array) - simply array will suffice, although generic names like this should be avoided.
I do not know why array[0].1[0] works
Let's pick this apart - your're accessing the first element in array via [0] and within that, the second element of the tuple .1, and lastly the first element of that valuearray. You could use array[0].value[0] for the same effect and make the code more readable.
but array[indexPath.section].row doesn't
That's because your array does not contain anything called row.
Use array[indexPath.section].value[indexPath.row].repoName instead.
Please try this code.
let dictData = arr[indexpath.section] //Element of section
let value = dictData["value"] //Value added in value in The element
let name = value[indexpath.row].reponame //Gives you name
I am trying to read nested array as follows but getting an error.
var inputArray = [1,[4,3],6,[5,[1,0]]]
func nestedArray(inputArray :[Any])
{
}
error: heterogeneous collection literal could only be inferred to
'[Any]'; add explicit type annotation if this is intentional var
inputArray = [1,[4,3],6,[5,[1,0]]]
You need
var inputArray:[Any] = [1,[4,3],6,[5,[1,0]]]
as you specify elements of different types Int , Array and nested Array
I have an array of Tag objects that have a property called tag, which is a string.
public struct Tag {
public let name: String
}
I would like to get an array of all of these name properties.
Given an array of tags, in Objective-C I would accomplish this with this line:
NSArray *tagNames = [tags valueForKey:#"name"]
How can I achieve the same thing in Swift?
I've tried:
let tagNames = tags.map({ $0.name })
But get a compiler error: "Value of type '[Tag]' has no member 'name'.
It looks like you have an array which contains another array of Tag objects.
This works for me:
let tags = [Tag(name: "tag1"), Tag(name: "tag2"), Tag(name: "tag3")]
let names = tags.map{$0.name }
print("Names: \(names)")
I have a dictionary containing UIColor objects hashed by an enum value, ColorScheme:
var colorsForColorScheme: [ColorScheme : UIColor] = ...
I would like to be able to extract an array of all the colors (the values) contained by this dictionary. I thought I could use the values property, as is used when iterating over dictionary values (for value in dictionary.values {...}), but this returns an error:
let colors: [UIColor] = colorsForColorSchemes.values
~~~~~~~~~~~~~~~~~~~~~^~~~~~~
'LazyBidrectionalCollection<MapCollectionView<Dictionary<ColorScheme, UIColor>, UIColor>>' is not convertible to 'UIColor'
It seems that rather than returning an Array of values, the values method returns a more abstract collection type. Is there a way to get an Array containing the dictionary's values without extracting them in a for-in loop?
As of Swift 2.0, Dictionary’s values property now returns a LazyMapCollection instead of a LazyBidirectionalCollection. The Array type knows how to initialise itself using this abstract collection type:
let colors = Array(colorsForColorSchemes.values)
Swift's type inference already knows that these values are UIColor objects, so no type casting is required, which is nice!
You can map dictionary to an array of values:
let colors = colorsForColorScheme.map { $0.1 }
Closure takes a key-value tuple from dictionary and returns just a value. So, map function produces an array of values.
More readable version of the same code:
let colors = colorsForColorScheme.map { (scheme, color) in
return color
}
UPDATE
From Xcode 9.0, dictionary values can be accessed using values property, which conforms to Collection protocol:
let colors = colorsForColorScheme.values
Typically you just want it as an array:
let colors = Array(dict.values)
and that's it.
Use colorsForColorScheme.map({$0.value})
you can create an extension on LazyMapCollection
public extension LazyMapCollection {
func toArray() -> [Element]{
return Array(self)
}
}
colorsForColorSchemes.values.toArray() or colorsForColorSchemes.keys.toArray()
Firstly, from the following statement, it seems that your variable(dictionary) name is colorsForColorScheme
var colorsForColorScheme: [ColorScheme : UIColor] = ...
while you are trying to get the values from colorsForColorSchemes dictionary when you did-
let colors: [UIColor] = colorsForColorSchemes.values
which should give you a compile time error. Anyways I am assuming that you had a typo, and you dictionary's name is colorsForColorSchemes. So, here is the solution-
As mentioned earlier, because of the type inference property in swift, your code can infer that the returned type from the .values function is returning an array of UIColor. However, Swift wants to be type-safe, so when you store the values in the colors array, you need to explicitly define that. For swift 5 and above, now you could just do following-
let colors = [UIColor](colorsForColorSchemes.values)
You can also use flatMap:
let colors = colorsForColorScheme.values.flatMap { $0 }
I've found this to be the most useful in Swift 5:
colorsForColorSchemes.allValues
See docs - https://developer.apple.com/documentation/foundation/nsdictionary/1408915-allvalues