I have two different arrays which am trying to map them to one object, using the information in the first array ModelOne id. I use two for loops to check if the id in model one appears in the second array if true create an object with model one id, name and array of all names in model two. From my implementation am not able to get the correct results.
// Model One
struct ModelOne: Codable {
let id: Int
let name: String
}
// Model two
struct ModelTwo: Codable {
let id: Int
let modelOneId: Int
let name: String
}
var arrayOne = [ModelOne]()
arrayOne.append(ModelOne(id: 1, name: "One"))
arrayOne.append(ModelOne(id: 2, name: "Two"))
var arrayTwo = [ModelTwo]()
arrayTwo.append(ModelTwo(id: 1, modelOneId: 1, name: "Some name"))
arrayTwo.append(ModelTwo(id: 2, modelOneId: 1, name: "Other name"))
arrayTwo.append(ModelTwo(id: 1, modelOneId: 2, name: "Name one"))
arrayTwo.append(ModelTwo(id: 2, modelOneId: 2, name: "Name two"))
struct MappedModel {
let id: Int
let name: String
let items: [String]
}
var arrayThree = [MappedModel]()
for i in arrayOne {
for x in arrayTwo {
if i.id == x.id {
arrayThree.append(MappedModel(id: i.id, name: i.name, items: [x.name]))
}
}
}
If I'm interpreting the issue correctly, you want the MappedModel to have the id and name from ModelOne, with items containing all of the names from the ModelTwo where modelOneId matches the ModelOne id.
If so, this would do the trick:
var combined = arrayOne.map { item1 in
MappedModel(id: item1.id, name: item1.name, items: arrayTwo.compactMap { $0.id == item1.id ? $0.name : nil})
}
Which yields:
[
MappedModel(id: 1, name: "One", items: ["Some name", "Other name"]),
MappedModel(id: 2, name: "Two", items: ["Name one", "Name two"])
]
Related
List<Cart> CARTLIST = [
Cart(productName: "productName", amount: 123, image: "image", quantity: 3, desc: "KG", prodId: 1),
Cart(productName: "productName", amount: 345, image: "image", quantity: 3, desc: "KG", prodId: 1),
];
How to get cart amount total?
I'd do:
var result = 0;
for (var cart in CARTLIST) {
result += cart.amount;
}
It's short, direct and readable.
If you insist on doing it in a single expression, you can do:
var result = CARTLIST.fold<int>(0, (acc, cart) => acc + cart.amount);
Or you can do it in more steps, first extract the amounts, then add them up:
var result = CARTLIST.map((cart) => cart.amount).reduce((v1, v2) => v1 + v2);
I have the following JSON response -
{
"type": "StudentSchema",
"version": 1,
"students": [
{
id: 1,
name: "John",
roll: "1234"
},
{
id: 2,
name: "David",
roll: "4434"
}
]
}
Then how can I extract the array in Karate with name John to do further validation?
e.g. I want to say if name == John then save the id
I am trying below but it does not seem to work -
* def userId = get[0] response $[?(#students.name == 'John')].id
* match userId == 2
Let say your JSON is
MyJson = {
"type": "StudentSchema",
"version": 1,
"students": [
{
id: 1,
name: "John",
roll: "1234"
},
{
id: 2,
name: "David",
roll: "4434"
}
]
}
Now as you want to get the ID for the student whose name is john you can get it by using JSON path
* def JSONpath = '$..students[?(#.name=='John')].id'
* def userId = karate.jsonPath(MyJson,JSONpath)
It will give you an array of ID which satisfy the json path condition and you can do your assertion from that.
Currently, I'm trying to use Swift's codable protocol to add and read custom objects to and from Firebase's database. I've been following the instructions in these docs. However, when I try to write to the database, I'm getting an error "FIRInvalidArgumentException: Nested arrays are not supported". But aren't they supported? I saw another post on here from a couple of years ago that addressed a similar issue but I don't understand what I did wrong here.
These are the Swift struct representations that implement Codable:
struct List: Codable {
var title: String
var date: String
var description: String
var data: [SectionHeaders: Array<Item>] = [
.produce: [],
.seafood: [],
.meat: [],
.deli: [],
.bakery: [],
.pantry: [],
.dairy: [],
.frozen: [],
.other: []
]
enum CodingKeys: String, CodingKey {
case name
case date
case description
case data = "items"
}
struct Item: Codable {
var name: String?
var quantity: String?
}
enum SectionHeaders: Int, Codable {
case produce = 0, seafood, meat, deli, bakery, pantry, dairy, frozen, other, total
enum CodingKeys: String, CodingKey {
case produce = "produce"
case seafood = "seafood"
case meat = "meat"
case deli = "deli"
case bakery = "bakery"
case pantry = "pantry"
case dairy = "dairy"
case frozen = "frozen"
case other = "other"
}
}
And this is the data representation I'm aiming to get:
"title": String,
"date": String,
"description": String,
"items": [
"header1": [{
"name": String,
"quantity": String
},
{
"name": String,
"quantity": String
}
],
"header2": [{
"name": String,
"quantity": String
},
{
"name": String,
"quantity": String
}
]
]
Any help would be great! Thanks in advance!
class product {
String name;
String price;
String quantity;
product({this.name, this.price, this.quantity});
}
void main() {
List<product> listofProducts = [
product(name: "A", price: "10"),
product(name: "B", price: "10"),
product(name: "C", price: "10"),
product(name: "D", price: "10"),
product(name: "E", price: "10"),
product(name: "F", price: "10")
];
print(listofProducts.indexOf(product(name: "B", price: "10")));
}
How do I find the index of the product(name: "B", price: "10") in listofProducts list.
since the items of your list are not primitve, they are reference types , you need to use the indexWhere method on the list
final index = listofProducts.indexWhere((product) => product.name == "B" && product.price == "10");
print(index)
this way you iterate over each element of the array of products and find the index of that item. becuase you are having reference types as items.
Alternative you can override == and hashCode so you change what Dart understands as equal of Product objects (default behavior is that objects are only equal if they are the same instance in memory).
By doing the following we change it so two Product objects are equal if they have the same name, price and quantity values.
import 'package:quiver/core.dart';
class Product {
String name;
String price;
String quantity;
Product({this.name, this.price, this.quantity});
#override
bool operator ==(dynamic other) {
if (other is Product) {
return other.name == name &&
other.price == price &&
other.quantity == quantity;
}
return false;
}
#override
int get hashCode => hash3(name, price, quantity);
}
void main() {
List<Product> listofProducts = [
Product(name: "A", price: "10"),
Product(name: "B", price: "10"),
Product(name: "C", price: "10"),
Product(name: "D", price: "10"),
Product(name: "E", price: "10"),
Product(name: "F", price: "10")
];
print(listofProducts.indexOf(Product(name: "B", price: "10"))); // 1
}
To implement the hashCode I can recommend use the quiver package which has the hash3 method to make it more convenient to combine the hash of 3 values.
I have following data contract available in constant variable data
[
{
id: 1,
name: "class1",
start_at: "2017-08-15T10:00:00.000Z",
end_at: "2017-08-15T10:30:00.000Z",
},
{
id: 2,
name: "class2",
start_at: "2017-08-15T10:00:00.000Z",
end_at: "2017-08-15T10:30:00.000Z",
},
......more data here.....
]
I want to return the specific set of data.
e.g data.select {|e| e[:id] = 1} should return following but instead it returns all data.
[
{
id: 1,
name: "class1",
start_at: "2017-08-15T10:00:00.000Z",
end_at: "2017-08-15T10:30:00.000Z",
}
]
Any idea what is wrong?
extracted_data = data.select {|e| e[:id] == 1}
== for comparison