How to show array values in different forms? - arrays

I need to implement such form
I get json data from server:
"category_attributes": [
[
{
"name": "IPhone",
"terms": [
{
"name": "iPhone 11"
},
{
"name": "iPhone 12"
}
],
},
{
"name": "Memory",
"terms": [
{
"name": "1024"
},
{
"name": "128"
}
]
}
]
]
struct EachCategory: Decodable, Hashable {
let name: String
let category_attributes: [[CategoriesAttributes]]
}
struct CategoriesAttributes: Decodable, Hashable {
let name: String
let terms: [CateroriesTerms]
}
struct CateroriesTerms: Decodable, Hashable {
let name: String
}
I need to show first object's values of terms array inside buttons, and memory in dropdown list. I can only show all array values in buttons https://imgur.com/a/ZPydwmE How can I show only first object in buttons, and other objects in different form?
VStack(alignment: .leading) {
ForEach(viewModel.categoryAttributes, id: \.self) { category in
ForEach(category, id: \.self) { attribute in
Text(attribute.name)
HStack {
ForEach(attribute.terms, id: \.self) { term in
Button {
print("Phone model is selected")
} label: {
Text("\(term.name)")
.padding()
.foregroundColor(Color.textFieldGrayColor)
}.background(Color.grayButton)
.cornerRadius(10)
.frame(height: 50)
}
}
}
}
}

Related

Retrieving related elements from MongoDB

I have the following data in MongoDB. Based alone on an id that I have available how can I retrieve all other entries where the player matches the player for my current id.
For example : find who the player for id 12 is, search all other entries that match that player name and return a list of all of them.
[
{_id: '62ecdf342f1193134043964c', id: '12', player: 'David Beckham', team: 'Manchester United'},
{_id: '62ecdf342f1193134043965c', id: '17', player: 'Cristiano Rolando', team: 'Manchester United'},
{_id: '62ecdf342f1193134043966c', id: '22', player: 'Cristiano Rolando', team: 'Juventus'},
{_id: '62ecdf342f1193134043967c', id: '42', player: 'David Beckham', team: 'Real Madrid'},
]
This is the code that I'm using to retrieve the one single entry that matches a specific id and then I'd also like to get the related entries.
export async function getStaticProps({ params }) {
const { db } = await connectToDatabase();
const jerseyA = await db
.collection("Jerseys")
.find({ id: params.jersey })
.sort()
.toArray();
const jersey = JSON.parse(JSON.stringify(jerseyA))[0];
return { props: { jersey } };
}
Now that you know the name, do another fetch like .find({player: jersey.player})
I'm not sure of the output format you want, but here's one way to return all documents that match the "player" name of the given "id".
db.Jerseys.aggregate([
{
"$match": {
// your id goes here
"id": "17"
}
},
{
"$lookup": {
"from": "Jerseys",
"localField": "player",
"foreignField": "player",
"as": "docs"
}
},
{"$unwind": "$docs"},
{"$replaceWith": "$docs"}
])
Example output:
[
{
"_id": "62ecdf342f1193134043965c",
"id": "17",
"player": "Cristiano Rolando",
"team": "Manchester United"
},
{
"_id": "62ecdf342f1193134043966c",
"id": "22",
"player": "Cristiano Rolando",
"team": "Juventus"
}
]
Try it on mongoplayground.net.
Just an addition to #rickhg12hs solution, to ignore the first record. You can use the following query to ignore the first record (where the id also matched) and the others.
db.Jerseys.aggregate([
{
"$match": {
"id": "12"
}
},
{
"$lookup": {
"from": "Jerseys",
"localField": "player",
"foreignField": "player",
"as": "docs"
}
},
{
"$unwind": "$docs"
},
{
"$replaceWith": "$docs"
},
{
"$match": {
"id": {
"$not": {
"$eq": "12"
}
}
}
}
])
A possible javascript translation of it, should be,
export async function getStaticProps({ params }) {
const { db } = await connectToDatabase();
const { jersey: id } = params;
const jerseyA = await db
.collection("Jerseys")
.aggregate([
{
"$match": {
id
}
},
{
"$lookup": {
"from": "Jerseys",
"localField": "player",
"foreignField": "player",
"as": "docs"
}
},
{
"$unwind": "$docs"
},
{
"$replaceWith": "$docs"
},
{
"$match": {
"id": {
"$not": {
"$eq": id
}
}
}
}
]).toArray();
const jersey = JSON.parse(JSON.stringify(jerseyA))[0];
return { props: { jersey } };
}

How to create nested array in realm without key(React Native)

{
"a": [
[
{
"_id": "57e55b64016c3551c025abc1",
"title": "Main Campus"
},
{
"_id": "5810e2e27064497f74ad4874",
"title": "Ahm Campus"
},
{
"_id": "5d5d2633a1d0680620ac3cce",
"title": "Baroda"
},
{
"_id": "5d5d3af3a1d0680620ac3ef8",
"title": "India"
}
],
[
{
"_id": "57e55b64016c3551c025abc1",
"title": "Main Campus"
},
{
"_id": "5810e2e27064497f74ad4874",
"title": "Ahm Campus"
},
{
"_id": "5d5d2633a1d0680620ac3cce",
"title": "Baroda"
},
{
"_id": "5d5d3af3a1d0680620ac3ef8",
"title": "India"
}
]
]
}
How to create the schema in the realm(React native) for this type of JSON object. I tried all possible ways but did not found any specific solution. Basically, it is a nested array where the second array does not have any specific key(I tried with key it works fine but I want to do it without adding key).
You can use something like:
const ParentSchema = {
name: "parent",
properties: {
key: "string",
values: "Value[]"
}
};
const ValueSchema = {
name: "Value",
embedded: true,
properties: {
_id: "string",
title: "string"
}
};
You can insert objects like:
realm.write(() => {
realm.create("Parent", { key: "a", values: [
{ _id: "57e55b64016c3551c025abc1", title: "Main Campus" },
{ _id: "5810e2e27064497f74ad4874", title: "Ahm Campus" }
]
});
});
Documentation: https://docs.mongodb.com/realm/node/data-model
As of now there is no way to insert direct value in Realm database without key so for now we need to modify data and then we can store in following schema.
const ParentSchema = {
name: "parent",
properties: {
a: "level[]"
}
};
const level = {
name: 'level',
properties: {
level: 'sites[]'
}
}
const sites = {
name: 'sites',
properties: {
sites: 'site[]'
}
}
const site = {
name: 'site',
properties: {
title: 'string?',
_id: 'string?',
version: 'int?',
}
}
Data modification need to done like following.
var a = {
level: []
}
data.a.map((Site, index) => {
const sites = []
Site.map((s) => { sites.push(s)})
a.level.push({sites})
})

How to get JSON array value in Swift using Codable

I'm having trouble getting the direction values from the following JSON:
"routeOptions": [
{
"name": "Jubilee",
"directions": [
"Wembley Park Underground Station",
"Stanmore Underground Station"
],
"lineIdentifier": {
"id": "jubilee",
"name": "Jubilee",
"uri": "/Line/jubilee",
"type": "Line",
"routeType": "Unknown",
"status": "Unknown"
}
}
]
I believe the directions is a JSON array, which at the moment I'm using Codable as below. I've managed to get the routeOptions name but can't seem to figure out how to get the directions as there's no specific key variable. Please can someone help?
struct RouteOptions: Codable {
let name: String?
let directions: [Directions]?
init(name: String, directions: [Directions]) {
self.name = name
self.directions = directions
}}
struct Directions: Codable {}
You need to handle directions as an array of String
struct RouteOptions: Codable {
let name: String
let directions: [String]
}
Here is an example where I fixed the json to be correct
let data = """
{ "routeOptions": [
{
"name": "Jubilee",
"directions": [
"Wembley Park Underground Station",
"Stanmore Underground Station"
],
"lineIdentifier": {
"id": "jubilee",
"name": "Jubilee",
"uri": "/Line/jubilee",
"type": "Line",
"routeType": "Unknown",
"status": "Unknown"
}
}
]}
""".data(using: .utf8)!
struct Root: Decodable {
let routeOptions: [RouteOptions]
}
struct RouteOptions: Codable {
let name: String
let directions: [String]
}
do {
let result = try JSONDecoder().decode(Root.self, from: data)
print(result.routeOptions)
} catch {
print(error)
}

How to get element from JSON array in array in array

I have a question about this JSON. How to get coordinates from here?
I try to use for(){} like code below but doesn't work.
item {
"type": "type1",
"features": [{
"type": "typeee1",
"geometry": {
"type": "Point",
"coordinates": [
-19.726330999999998,
41.360610000000001
]},
"properties": {
"id_strada": "1433",
"nome_strada": "test3",
} },
{
"type": "typeee2",
"geometry": {
"type": "Point",
"coordinates": [
19.726344999999998,
26.36063
] },
"properties": {
id_strada": "13",
"nome_strada": "test5",
} },
{
"type": "typeee3",
"geometry": {
"type": "Point",
"coordinates": [
19.726358999999999,
98.36065
] },
"properties": {
id_strada": "14",
"nome_strada": "test34",
} }, {
"type": "typeee5",
"geometry": {
"type": "Point",
"coordinates": [
19.726372999999999,
55.360669999999999
] },
"properties": {
id_strada": "14335",
"nome_strada": "test39",
} }],
"last_update": "15-08-2019 15:04:45"
}
function that call JSON is like below.
item: Item[];
this.ws.getitems().subscribe(
item => {
this.item = item;
console.log('this.item.length', this.item.length)
for (let i = 0; i < this.item.length; i++) {
}
}
);
this.item.length is undefined
My question is, how to get coordinates in here?
Can you ask me any idea please?
Thanks!
You don't have an array in an array in an array. You have an array in an object in an object in an array in an object.
interface Feature {
type: string;
geometry: {
type: string;
coordinates: [ number, number ];
};
properties: {
id_strada: string;
nome_strada: string;
};
}
interface Item {
type: string;
features: Feature[];
last_update: string;
}
const items$: Observable<Item> = this.ws.getItems();
const coordinates$: Observable<[number, number]> = items$.pipe(
switchMap((item: Item) => of(
...item.features.map((feature: Feature) => feature.geometry.coordinates)
)),
);
coordinates$.subscribe((coordinates: [number, number]) => console.log(coordinates));
It is really unclear exactly what your intention is here. Your Item object has multiple coordinates within it. Do you intend to link all of the coordinates, or just the first, or do you want to split them by feature? I've provided you a way to just have an unlinked stream of all coordinates you ever receive. You'll have to figure out what it is you want to do with that.
If you were already in item, coordinates are at item.geometry.coordinates
If your supplied json was x, you could get the first coordinates at x.features[0].geometry.coordinates.
You could find each set of coordinates with:
x.features.forEach(item => {
let coords = item.geometry.coordinates
// do something with coords
})

Swift Codable: Array of Dictionaries

I have a JSON object from Yelp and I cannot figure out how to access the title in categories using Swift Codable. This is the JSON (with some elements removed for ease of reading):
{
"businesses": [
{
"id": "fob-poke-bar-seattle-2",
"name": "FOB Poke Bar",
"is_closed": false,
"review_count": 421,
"categories": [
{
"alias": "poke",
"title": "Poke"
},
{
"alias": "salad",
"title": "Salad"
},
{
"alias": "hawaiian",
"title": "Hawaiian"
}
],
"rating": 5,
"coordinates": {
"latitude": 47.6138005187095,
"longitude": -122.343868017197
},
"price": "$$",
"location": {
"city": "Seattle",
"zip_code": "98121",
"country": "US",
"state": "WA",
"display_address": [
"220 Blanchard St",
"Seattle, WA 98121"
]
},
}
Here it is in JSON Viewer
I access first level properties like name easily, and I access lattitude and longitude like so:
class Business: Codable {
var name: String
var rating: Double
var coordinates: Coordinates
struct Coordinates: Codable {
var latitude: Double
var longitude: Double
init(lat: Double, long: Double) {
self.latitude = lat
self.longitude = long
}
}
init(name: String, rating: Double, coordinates: Coordinates) {
self.name = name
self.rating = rating
self.coordinates = coordinates
self.categories = categories
}
}
Could anyone please point me in the right direction towards accessing categories -> title? Coordinates was easy to access but categories is an array of dictionaries. Thank you!
It's the same pattern like Coordinates except the value for categories is an array:
struct Root : Decodable {
let businesses : [Business]
}
struct Business: Decodable {
let name: String
let rating: Int
let coordinates: Coordinates
let categories : [Category]
struct Coordinates: Codable {
let latitude: Double
let longitude: Double
}
struct Category: Codable {
let alias: String
let title: String
}
}
let root = try decoder.decode(Root.self, from: data)
for business in root.businesses {
for category in business.categories {
print(category.title)
}
}

Resources