How to create an array of dictionaries? - arrays

new to programming!
I'm trying to create an array of dictionaries inside a struct in Swift like so:
var dictionaryA = [
"a": "1",
"b": "2",
"c": "3",
]
var dictionaryB = [
"a": "4",
"b": "5",
"c": "6",
]
var myArray = [[ : ]]
myArray.append(dictionaryA)
myArray.append(dictionaryB)
This works fine in a playground, but when I put it into an Xcode project, inside a struct, the lines with the append function produce the error "Expected declaration".
I've also tried using the += operator with the same result.
How can I successfully construct this array inside the struct?

From your error Expected declaration, I assume you are doing like:
struct Foo {
var dictionaryA = [
"a": "1",
"b": "2",
"c": "3",
]
var dictionaryB = [
"a": "4",
"b": "5",
"c": "6",
]
var myArray = [[ : ]]
myArray.append(dictionaryA) // < [!] Expected declaration
myArray.append(dictionaryB)
}
This is because you can place only "declarations" in the struct body, and myArray.append(dictionaryA) is not a declaration.
You should do that somewhere else, for example in the initializer. The following code compiles.
struct Foo {
var dictionaryA = [
"a": "1",
"b": "2",
"c": "3",
]
var dictionaryB = [
"a": "4",
"b": "5",
"c": "6",
]
var myArray = [[ : ]]
init() {
myArray.append(dictionaryA)
myArray.append(dictionaryB)
}
}
But as #AirspeedVelocity mentioned, you should provides more information about myArray, or myArray would be Array<NSDictionary> which I think you don't expect.
Anyway, the correct solution would vary depending on what you really trying to do:
Maybe or maybe not, what you want is something like:
struct Foo {
static var dictionaryA = [
"a": "1",
"b": "2",
"c": "3",
]
static var dictionaryB = [
"a": "4",
"b": "5",
"c": "6",
]
var myArray = [dictionaryA, dictionaryB]
}
But, I don't know, why don't you just:
struct Foo {
var myArray = [
[
"a": "1",
"b": "2",
"c": "3",
],
[
"a": "4",
"b": "5",
"c": "6",
]
]
}

The problem lies with this line:
var myArray = [[ : ]]
You need to tell Swift what type myArray is – [[:]] isn’t enough information.
You can either do it the explicit way:
var myArray: [[String:String]] = [[ : ]]
Or, if practical, implicitly using the first or both values you plan to put in:
var myArray = [dictionaryA]
var myArray = [dictionaryA,dictionaryB]
(as an alternative to the explicit empty version, you can also write var myArray = [[String:String]](), which is shorthand for var myArray = Array<Dictionary<String,String>>())

var arrayOfDict = [[String: Int]]()
// Create a dictionary and add it to the array.
var dict1: [String: Int] = ["age": 20]
arrayOfDict.append(dict1)
// Create another dictionary.
var dict2: [String: Int] = ["rank": 5].
arrayOfDict.append(dict2)
// Get value from dictionary in array element 0.
if let value = arrayOfDict[0]["age"] {
print(value)
}
Output
20

Or you can use an array of tuples that´s even easier, like this:
var myArray:[(a:String,b:String,c:String)] = []
And append any element you need later:
self.myArray.append((a:"A",b:"B",c:"c"))
And to use them just:
self.myArray[index].a
self.myArray[index].b
self.myArray[index].c

Related

Calculation on dynamic data in React

This array can be fetched by .map in return()
[
{
"a": "3",
"Count": "3",
"b": "299.98999786376953",
"c": "30",
"d": "30"
},
{
"a": "9",
"Count": "1",
"b": "99.98999786376953",
"c": "10",
"d": "9"
}
]
I want to apply formulas on it like:
a = a/Count;
b = (b/(Count*10))*100;
c = (c/(Count*10))*100;
d = (d/(Count*10))*100;
Also find e = (a+b+c+d)/4;
then display them in each table row's data using .map
I tried npmjs.com/package/react-equation, it can do calculations directly in return() however don't fetch dynamic variables of array inside return(). I also tried creating a function outside return add(a,b){return a+b) and calling it inside return(), neither do it work and tried some other methods as well.
Here is a sample code that can help you continue your work. It uses map to transform your string array to float array and also return the new calculated objects
const array = [
{
"a": "3",
"Count": "3",
"b": "299.98999786376953",
"c": "30",
"d": "30"
},
{
"a": "9",
"Count": "1",
"b": "99.98999786376953",
"c": "10",
"d": "9"
}
]
const newArray = array.map(obj => {
const a = parseFloat(obj.a) / parseFloat(obj.Count);
const b = (parseFloat(obj.b)/(parseFloat(obj.Count) * 10)) * 100
const c = (parseFloat(obj.c)/(parseFloat(obj.Count) * 10)) * 100
const d = (parseFloat(obj.d)/(parseFloat(obj.Count) * 10)) * 100
return { a, b, c, d, e: (a+b+c+d)/4}
})
console.log(array, newArray)
I don't think you can really use map because you're doing different calculations for a and for b,c,d and for e, and also because the calcultions on a depends on value of Count. You could just define a function that accepts the entire object and performs the calculations like so:
const performCalculations = (obj) => {
obj.a = obj.a / obj.Count;
obj.b = (obj.b/(obj.Count*10))*100;
obj.c = (obj.c/(obj.Count*10))*100;
obj.d = (obj.d/(obj.Count*10))*100;
obj.e = (obj.a + obj.b + obj.c + obj.d)/4;
return obj;
}
Edit: you can use map see #Apostolos answer

Split the array and get value [React native]

I am developing the react native application and I want to split the array but I can't understand how to do that,
[{"dtCreatedOn": "2021-06-01T03:28:21.450Z", "flgIsActive": true, "inTagId": 2, "stTags": "Song"}, "3", "6", "7", "8"]
I have something like the above array, I want to get the value of the inTagId and also last integer value "3", "6", "7", "8" from this array
var a = [{"dtCreatedOn": "2021-06-01T03:28:21.450Z", "flgIsActive": true, "inTagId": 2, "stTags": "Song"}, "3", "6", "7", "8"]
var tagID = a[0].inTagId
var b = Object.keys(a)
var lastInteger = b[(b.length-1)]
var test = [{"dtCreatedOn": "2021-06-01T03:26:44.910Z", "flgIsActive": true, "inTagId": 1, "stTags": "Emotion"},"4","5","6"]
var tags = [];
test.map(function(ele) {
if(typeof ele === 'object')
{
tags.push(ele.inTagId);
}
else
{
tags.push(ele)
}
});
tags.join(',')

Convert Array of Objects into Array of Array of strings

In my angular app, I get the values from service as an array of objects like below.
temp= [
{
"a": "AAA",
"b": "bbbb",
"c": "CCCC",
"d": "ddddd",
},
{
"a": "lmn",
"b": "opq",
"c": "rst",
"d": "uvw",
}
]
I need to format this temp to array of array of strings:
newTemp =
[
['AAA', 'bbbb', 'CCCC', 'ddddd'],
['lmn', 'opq', 'rst', 'uvw'],
];
Should we need to do a forloop on each object or is there any straight forward way.
You can use Array.map
let newArray = arr.map(a => Object.values(a))
If you cant use Object.values
let newArray = arr.map(a => Object.keys(a).map(k => a[k]))
Output
(2) [Array(4), Array(4)]
0:(4) ["AAA", "bbbb", "CCCC", "ddddd"]
1:(4) ["lmn", "opq", "rst", "uvw"]
Try the following :
temp= [
{
"a": "AAA",
"b": "bbbb",
"c": "CCCC",
"d": "ddddd",
},
{
"a": "lmn",
"b": "opq",
"c": "rst",
"d": "uvw",
}
]
var newTemp = [];
temp.forEach(function(obj){
var arr = [];
Object.keys(obj).forEach(function(key){
arr.push(obj[key]);
})
newTemp.push(arr);
});
console.log(newTemp);

how to use for loop make an array which contains something like a dictionary

I want to create an array something like this
array=["1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8"]
It's something like a dictionary, every value needs to be a key:value pair,
so my problem is how to init this type of array? The following is my work, it doesn't work.
array=[String:String]()
for i in 0...7{
array.append(String(i):String(i))
}
every line has a bug!!
plz help
Its not something like Dictionary it is Dictionary, if you want to make a dictionary you can go like this way.
var dictionary = [String:String]()
for i in 0...7{
dictionary[String(i)] = String(i)
}
print(dictionary)
["0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7"]
In addition to Nirav D's answer; I feel the following may help:
There is a method updateValue(_:​for​Key:​) that updates (or adds new key-value pair if the key does not exist) the value for given key.
So your code would look like this:
var array = [String:String]()
for i in 0...7 {
array.updateValue(String(i), forKey: String(i))
}
print(array)
// Output
["2": "2", "1": "1", "6": "6", "4": "4", "3": "3", "7": "7", "0": "0", "5": "5"]
Swift is always amazing you can define += operator that make it easier. So the code will be as follows:
// Defining += operator
func += <K, V> (inout left: [K:V], right: [K:V]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
// Usage
var array = [String:String]()
for i in 0...7{
array += [String(i):String(i)]
}
print(array)
// Output
["2": "2", "1": "1", "6": "6", "4": "4", "3": "3", "7": "7", "0": "0", "5": "5"]

Remove value from Array of Dictionaries

How I can remove a dict from an array of dictionaries?
I have an array of dictionaries like so: var posts = [[String:String]]() - and I would like to remove a dictionary with a specific key, how would I proceed? I know that I can remove a value from a standard array by doing Array.removeAtIndex(_:) or a dictionary key by doing key.removeValue(), but an array of dictionaries is more tricky.
Thanks in advance!
If I understood you questions correctly, this should work
var posts: [[String:String]] = [
["a": "1", "b": "2"],
["x": "3", "y": "4"],
["a": "5", "y": "6"]
]
for (index, var post) in posts.enumerate() {
post.removeValueForKey("a")
posts[index] = post
}
/*
This will posts = [
["b": "2"],
["y": "4", "x": "3"],
["y": "6"]
]
*/
Since both your dictionary and the wrapping array are value types just modifying the post inside of the loop would modify a copy of dictionary (we created it by declaring it using var), so to conclude we need to set the value at index to the newly modified version of the dictionary
Removing all Dictionaries with a given key
let input = [
[
"Key 1" : "Value 1",
"Key 2" : "Value 2",
],
[
"Key 1" : "Value 1",
"Key 2" : "Value 2",
],
[
"Key 1" : "Value 1",
"Key 2" : "Value 2",
"Key 3" : "Value 3",
],
]
let keyToRemove = "Key 3"
//keep dicts only if their value for keyToRemove is nil (meaning key doesn't exist)
let result = input.filter{ $0[keyToRemove] == nil }
print("Input:\n")
dump(input)
print("\n\nAfter removing all dicts which have the key \"\(keyToRemove)\":\n")
dump(result)
You can see this code in action here.
Removing the only the first Dictionary with a given key
var result = input
//keep dicts only if their value for keyToRemove is nil (meaning key doesn't exist)
for (index, dict) in result.enumerate() {
if (dict[keyToRemove] != nil) { result.removeAtIndex(index) }
}
print("Input:\n")
dump(input)
print("\n\nAfter removing all dicts which have the key \"\(keyToRemove)\":\n")
dump(result)
You can see this code in action here.

Resources