["list": Optional([Optional(["phone": Optional("+51263153765"), "name": Optional("Peter Agent"), "__typename": Optional("User"), "email": Optional("peter#pety.com")]), Optional(["name": Optional("Thomas Agent"), "__typename": Optional("User"), "email": Optional("email#gmail.biz"), "phone": Optional("+1313131231")])]), "__typename": Optional("CompareUsers")]
How can I access the value of each element of each array in the [list Optional([..])]
So I can put use the value like so -->
let email: [String] = []
for contact in (the list) {
email.append(contact.email)
}
and same for the phone and the name, if someone got a big brain related to swift please help.
let listDictionary = ["list": Optional([Optional(["phone": Optional("+51263153765"),
"name": Optional("Peter Agent"),
"__typename": Optional("User"),
"email": Optional("peter#pety.com")]),
Optional(["name": Optional("Thomas Agent"),
"__typename": Optional("User"),
"email": Optional("email#gmail.biz"),
"phone": Optional("+1313131231")])]),
"__typename": Optional("CompareUsers")]
if let listArray = listDictionary["list"] {
for data in listArray {
if let personData = data {
if let phone = personData["phone"], let name = personData["name"], let email = personData["email"], let type = personData["__typename"] {
print("User: \(name) of type: \(type), has phone number: \(phone) and email: \(email)")
}
}
}
}
Related
I have an Encoded String:
("[{"carMake":"Mercedes","phone":"03001234567","insurancePolicyNo":"0123456","email":"a#g.com","full_name":"Steven Fin","registrationNo":"02134","insuranceProvider":"Michael","carModel":"Benz"}, {"carMake":"Audi","phone":"03007654321","insurancePolicyNo":"654321","email":"b#g.com","full_name":"Flemming Smith","registrationNo":"4325","insuranceProvider":"Buttler","carModel":"A3"}]")
I want to convert this into JSON array like this:
[
{
"full_name": "Steven Finn",
"insuranceProvider": "Michael",
"insurancePolicyNo": "0123456",
"registrationNo": "02134",
"carMake": "Mercedes",
"carModel": "Benz",
"email": "a#g.com",
"phone": "03001234567"
},
{
"full_name": "Flemming Smith",
"insuranceProvider": "Buttler",
"insurancePolicyNo": "654321",
"registrationNo": "4325",
"carMake": "Audi",
"carModel": "A3",
"email": "b#g.com",
"phone": "03007654321"
}
]
After some searching, what I did was converting it to Dictionary, which results in:
[["registrationNo": 02134, "carModel": Benz, "phone": 03001234567, "email": a#g.com, "insuranceProvider": Michael, "insurancePolicyNo": 0123456, "carMake": Mercedes, "full_name": Steven Finn], ["carModel": A3, "insuranceProvider": Buttler, "carMake": Audi, "insurancePolicyNo": 654321, "full_name": Flemming Smith, "registrationNo": 4325, "phone": 03007654321, "email": b#g.com]]
Which is not the desired result.
Did anyone knows how to achieve my desired array?
your so called Encoded String is already json data. Try this to decode it into a Car model:
struct Car: Codable {
let carMake, phone, insurancePolicyNo, email: String
let full_name, registrationNo, insuranceProvider, carModel: String
}
struct ContentView: View {
var body: some View {
Text("testing")
.onAppear {
let str = """
[{"carMake":"Mercedes","phone":"03001234567","insurancePolicyNo":"0123456","email":"a#g.com","full_name":"Steven Fin","registrationNo":"02134","insuranceProvider":"Michael","carModel":"Benz"}, {"carMake":"Audi","phone":"03007654321","insurancePolicyNo":"654321","email":"b#g.com","full_name":"Flemming Smith","registrationNo":"4325","insuranceProvider":"Buttler","carModel":"A3"}]
"""
do {
let data = str.data(using: .utf8)!
let response = try JSONDecoder().decode([Car].self, from: data)
print("\n---> response \(response)")
} catch {
print(" error \(error)")
}
I am new to React-Native i am building a sample app, But i ha d small problem with this.state.array , I want a particular element value from array
my array is
this.state.userDetail: [
Object {
"creation_Date": "2019-10-22T06:34:52.000Z",
"mobile": 9985849955,
"name": "siva",
"password": "123456",
"picture_url": "5.jpg",
"role": "",
"user_id": 1,
},
]
````````````````````````````````````````
In the above array i want user_id value ,
i tried different methods like
```````````````````````````
this.setState({ user_id: this.state.user_Details.user_id })
const item_id = this.state.user_Details.map((item) => { item.user_id });
var item_id = this.state.user_Details.filter(userDetails => { return userDetails[7]; })
``````````````````````````````````````````
but nothing will work i want only user_id value to update the users table , So please any help ..
If you wish to extract the user_id SPECIFICALLY from this example:
[
{
"creation_Date": "2019-10-22T06:34:52.000Z",
"mobile": 9985849955,
"name": "siva",
"password": "123456",
"picture_url": "5.jpg",
"role": "",
"user_id": 1,
},
]
and assuming this data is in your this.state.userDetail property.
The only thing you need is:
this.state.userDetail[0].user_id
Why this might not be working for you:
this.state.userDetail: [
Object { /// What's Object?
And if you are trying to parse more than 1 entry in the array unlike your example, you first need to select a certain entry with a 'for' loop or a .map() function.
I think you want to get one index user id, so I give the following code:
// define it in the constructor, and it may have more than one items
this.state.userDetail: [
{
"creation_Date": "2019-10-22T06:34:52.000Z",
"mobile": 9985849955,
"name": "siva",
"password": "123456",
"picture_url": "5.jpg",
"role": "",
"user_id": 1,
},
]
// do not directly assign use this.state.x
let copyUserDetails = {...this.this.state.user_Details}
let userIdsArray = copyUserDetail.map((item) => { return item.user_id });
let itemId = userIdsArray[0]
console.log("the first user Id is",itemId)
// if you only want to the user_id, you can directly copyUserDetails[0].user_id
let userId = copyUserDetails[0].user_id
console.log("the first user Id is ==> ",userId)
this.setState({ user_id: itemID })
// the filter is accordng some condtion to return a new arry
let itemFilterArray = copyUserDetails.filter((element,i) => {
// filter the item which match some condition, for example the uerId not equal
//0
if(element.user_id !== 0){
return element
}
})
according to your require, I give the following code:
//if you do not have many userInfo
constructor(props){
super(props)
this.state= {
user_Details: {
"creation_Date": "2019-10-22T06:34:52.000Z",
"mobile": 9985849955,
"name": "siva",
"password": "123456",
"picture_url": "5.jpg",
"role": "",
"user_id": 1,
}
}
// somewhere you want the userId
getUserId = () => {
return this.state.user_Details.user_id
}
}
//if you have many userinfo
constructor(props){
super(props)
this.state= {
user_Details: [{
"creation_Date": "2019-10-22T06:34:52.000Z",
"mobile": 9985849955,
"name": "siva",
"password": "123456",
"picture_url": "5.jpg",
"role": "",
"user_id": 1,
}]
}
// somewhere you want the some index userId
getUserId = (index) => {
// do not directly assign use this.state.x
let copyUserDetails = {...this.this.state.user_Details}
return copyUserDetails[index].user_id
}
//somwhere you want all the userId
getUserId = () => {
// do not directly assign use this.state.x
let copyUserDetails = {...this.this.state.user_Details}
let userIdArray = copyUserDetail.map((item) => { return item.user_id });
return userIdArray
}
}
and I suggest you can read the api about json and array
I'm trying to pass some datas in my parameters to send to a server. But I'm facing some difficulties to build the params.
I have tried to loop through the array to add the dictionary which consists of the mobile and name but I'm not sure on how to build it properly as it return only first element of the array. I don't know how to append everything in the array.
var parameters: [String: Any] = ["invitations": [
["mobile": "1234567",
"name": "John1"]
]
]
for (item1, item2) in zip(arrName, arrNumber){
parameters = ["invitations": [
"mobile" : "\(item2)",
"name" : "\(item1)"]
]
}
This is the JSON I'm trying to build in the params.
{
"invitations": [
{
"mobile": "1234456",
"name": "Paul"
},
{
"mobile": "1234456",
"name": "Paul1"
},
{
"mobile": "1234456",
"name": "Paul2"
}
]
}
let arr = zip(arrNumber,arrName).map { ["mobile":$0,"name":$1] }
var parameters: [String: Any] = ["invitations": arr]
print(parameters)//["invitations": [["name": "Paul", "mobile": "1234456"], ["name": "Paul1", "mobile": "1234456"], ["name": "Paul2", "mobile": "1234456"]]]
do {
let json = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
let convertedString = String(data: json, encoding: .utf8)
print(convertedString)
} catch let error {
print(error.localizedDescription)
}
{ "invitations": [
{
"name": "Paul",
"mobile": "1234456"
},
{
"name": "Paul1",
"mobile": "1234456"
},
{
"name": "Paul2",
"mobile": "1234456"
} ] }
I know how to operate on array of objects but never had the necessity to push one array data into another. I need to push an array of objects into another array with only 2 fields of the object. Right now my object format is somewhat like this
data: [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
I want to push this into another array but I want only courseid and name in the object. I've read that we need to initialise the object in the constructor, use slice() and a few other functions and then push but I don't know how can I do it for mine since I need to push one array data into another.Kindly someone help me in this regard.
You're looking for the array map() method:
const newArray = array.map(o => {
return { name: o.name, courseid: o.courseid };
});
Try this:
let data = [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
let other = []; // your other array...
data.map(item => {
return {
courseid: item.courseid,
name: item.name
}
}).forEach(item => other.push(item));
console.log(JSON.stringify(other))
// => [{"courseid":"1","name":"Btech"},{"courseid":"2","name":"BCom"}]
You can simply do it like this.
//assign your array of object to variable
var youArray:Array<any>= [{
"name": "Btech",
"courseid": "1",
"courserating": 5,
"points": "100",
"type": "computers"
},
{
"name": "BCom",
"courseid": "2",
"courserating": 5,
"points": "100",
"type": "computers"
}];
var resultArray:Array<any>=[] //empty array which we are going to push our selected items, always define types
youArray.forEach(i=>{
resultArray.push(
{
"name":i.name,
"courseid":i.courseid
});
});
console.log(resultArray)
if you still have doubts about this.please follow this url
Map to a returning JSON data, subscribe it to an existing array or an empty one. #typescript
let pictimeline= [];
var timeline = this.picService.fetchtimeline(this.limit)
.map((data : Response) => data.json())
.subscribe(pictimeline=> this.pictimeline = pictimeline);
console.log(this.pictimeline);
I want to save the subcategory data in this form [[value1,value2,...],[value1, value2],[value1],.....] in the following code
var subcategories = [SubCategory]()
for (_, item) in json {
//do something with item.id, item.name
for (_, subcategory) in item["subcategory"] {
let subcategory = SubCategory(
id: Int(subcategory ["id"].stringValue),
name: subcategory ["name"].string,
desc: subcategory ["desc"].string,
image: subcategory ["image"].string,
coupon: Int(subcategory ["coupon"].stringValue),
icon: subcategory ["icon"].string,
order: Int(subcategory ["order"].stringValue),
aname: subcategory ["aname"].string,
options: Int(subcategory ["options"].stringValue),
items: subcategory ["items"].arrayObject
)
subcategories.append(subcategory)
}
print(subcategories.count)
for sub in subcategories {
print(sub.name)
print(sub.id)
print(sub.desc)
self.SUBCATNAME.append(sub.name!)
self.SUBARRAY?.append(self.SUBCATNAME)
}
print(self.SUBCATNAME)
print(self.SUBARRAY)
}
I need to append all the subcategory name in an array of dictionary like the above structure. Here i created SUBARRAY as var SUBARRAY:[[String]] = []. but the value is coming as nil. Here i am getting the json data from Api using Swiftyjson. How to implement this??
my sample json data is as below:
like wise so many subcategories are there
[
{
"id": "244",
"name": "PIZZAS",
"subcategory": [
{
"id": "515",
"name": "MARGARITA",
"description": "Cheese and Tomato",
"image": "",
"icon": "",
"coupon": "1",
"order": "1",
"aname": "",
"options": "2"
},
{
"id": "516",
"name": "ABC",
"description": "HNDDSGHFD",
"image": "",
"icon": "",
"coupon": "1",
"order": "1",
"aname": "",
"options": "2",
},
{
"id": "516",
"name": "DEF",
"description": "HFDGFJJFHFKH",
"image": "",
"icon": "",
"coupon": "1",
"order": "1",
"aname": "",
"options": "2",
}
]
},
{
......
}
]
if you try this code
for (NSDictionary *dictionary in ArrCategory)
{
NSMutableArray *sub_cat_data=[dictionary objectForKey:#"sub_cat_data"];
for (NSDictionary *sub_cat_dict in sub_cat_data)
{
NSMutableArray *sub_cat_data=[sub_cat_dict objectForKey:#"sub_data"];
for (NSDictionary *dictionary1 in sub_cat_data)
{
NSMutableDictionary *Dic_Sub_cat=[[NSMutableDictionary alloc]init];
NSString *str_dic_id=[dictionary1 objectForKey:#"sub_id"];
NSString *str_dic_name=[dictionary1 objectForKey:#"sub_name"];
[Dic_Sub_cat setObject:str_dic_id forKey:#"sub_id"];
[Dic_Sub_cat setObject:str_dic_name forKey:#"sub_name"];
[Dic_Sub_cat setObject:#"0" forKey:#"sub_Chekid"];
[New_ArrCategory addObject:Dic_Sub_cat];
}
}
}
swift example
if let results: NSMutableArray = jsonResult["data"] as? NSMutableArray
{
var ArrMoodtype2 : NSMutableArray!
ArrMoodtype2 = NSMutableArray()
ArrMoodtype2 = results
ArrFeel = NSMutableArray()
for var i = 0; i < ArrMoodtype2.count; i++
{
var Dic : NSMutableDictionary!
Dic = NSMutableDictionary()
let tempDic: NSMutableDictionary = ArrMoodtype2[i] as! NSMutableDictionary
let strMoodCatID = tempDic ["mood_cat_id"] as! String
let strMoodID = tempDic ["mood_id"] as! String
let strMoodImage = tempDic ["mood_image"] as! String
let strMoodName = tempDic ["mood_name"] as! String
Dic.setObject(strMoodCatID, forKey: "mood_cat_id")
Dic.setObject(strMoodID, forKey: "mood_id")
Dic.setObject(strMoodImage, forKey: "mood_image")
Dic.setObject(strMoodName, forKey: "mood_name")
ArrFeel.addObject(Dic)
}
}