I have a dictionary which I want to append some items.
**This is my dictionary which I want to achieve: **
let parameters: [String: Any] = [
{
"ResultsList": [{
"UserId": "b806e283-066f-4081-aafe-1fe216a57c35",
"FriendUserId": "7a2ec150-cdb3-4600-84f8-2dab970bfa0c",
"TransferDate": "2017-11-23",
"UserAnswers": [{
"AnswerId": "b7562603-614d-11e7-a7e0-484d7ee0cd26",
"LastAnsweredDate": "2017-11-23",
"QuestionId": "0b60f35e-5d80-11e7-a7e0-484d7ee0cd26"
},
{
"AnswerId": "b7562603-614d-11e7-a7e0-484d7ee0cd26",
"LastAnsweredDate": "2017-11-23",
"QuestionId": "0b60f35e-5d80-11e7-a7e0-484d7ee0cd26"
}
]
}]
}
]
And this is my current dictionary which I want to make the loop and add the items.
let parameters: [String: Any] = [
{
ResultsList: [
{
UserId: “b806e283-066f-4081-aafe-1fe216a57c35”
FriendUserId: “7a2ec150-cdb3-4600-84f8-2dab970bfa0c”
TransferDate: “2017-11-23”
UserAnswers: [
{
AnswerId: “b7562603-614d-11e7-a7e0-484d7ee0cd26"
LastAnsweredDate: “2017-11-23”
QuestionId : “0b60f35e-5d80-11e7-a7e0-484d7ee0cd26"
}
]
}
]
}
]
I have 3 arrays which I want to loop through and append to the dictionary
var AnswerId = [ “b7562603-614d-11e7-a7e0-484d7ee0cd26", “aasdaas-614d-11e7-a7e0-484d7ee0cd26", “b756asd03-614d-11e7-a7e0-484d7ee0cd26"]
var LastAnsweredDate = [“2017-11-23”, “2017-11-23”, “2017-11-22”]
var QuestionId = [“0b60f35e-5d80-11e7-a7e0-484d7ee0cd26",“asdasd-5d80-11e7-a7e0-484d7ee0cd26",“asdasd-5d80-11e7-a7e0-484d7ee0cd26"]
Can someone please help to achieve this result?
Related
How do I flatten a nested array?
[
{
"page": 1,
"items": [
{
"addresses": [
"hello1",
"hello2"
]
}
]
},
{
"page": 2,
"items": [
3,
{
"addresses": [
"hello3",
"hello4"
]
}
]
},
{
"page": 3,
"items": [
3,
4
]
}
];
Desired output ist:
["hello1", "hello2", "hello3", "hello4"]
import 'dart:convert';
main() {
const jsonString =
'[{"page":1, "items": [{"addresses": ["hello1","hello2"]}]}, {"page":2, "items": [3, {"addresses": ["hello3","hello4"]}]}, {"page":3, "items": [3, 4]}]';
final items = jsonDecode(jsonString) as List;
final x = items.expand((p) => p["items"]).expand((p) => p["addresses"]);
print(x);
}
Ok, so you have a list of maps that look like this:
{
page: int,
items: List<{
addresses: List<String>
}>
except sometimes the items are just numbers, you want to get all addresses on a single list, here is how I would do it:
List<String> result = [];
p.forEach((obj) {
final objMap = obj as Map<String, dynamic>
objMap['items'].forEach((item) {
if (item is Map<String, dynamic>) {
result.addAll(item['addresses'] as List<String>);
}
});
});
A bit clunky, I know, but I think it will do the trick
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 have tier to get all value from this jsonResult i want array from this like "projectArray","msg","msg2" and string like "output" ,"output_prg" i only get first array value how to get other values?
This is my result
{
"project": [{
"name": [{
"sac": "sachin",
"sag": "sagar"
}]
}, {
"output": " true",
"msg1": [{
"emp": "001",
"empname": "sachin"
}, {
"emp": "002",
"empname": "sagar"
}]
}, {
"output_prg": " true",
"msg2": [{
"id": "1",
"pr_code": "SD"
}, {
"id": "002",
"pr_code": "SJ"
}]
}]
}
This is my code
if let array = response.result.value as? NSDictionary
{
print(array)
let mainArray = array["project"] as? [[String:Any]]
print(mainArray!)
for item in mainArray!
{
print(item)
let status = item["name"]
print(status!)
}
}
Thank you in advance
Try This---->
//to get JSON return value
if let array = response.result.value as? NSDictionary
{
print(array)
let mainArray = array["project"] as? [[String:Any]]
print(mainArray?.count as Any)
if (mainArray?.count)!>0
{
let name = mainArray?[0]
let project_status = name?["name"] as? [[String:Any]]
print(name!)
}
if (mainArray?.count)!>1
{
let output = mainArray?[1]
print(output!)
}
if (mainArray?.count)!>2
{
let output_prg = mainArray?[2]
let Output_getProject = output_prg?["output_prg"]
}
}
}
Happy Coading :-)
I am currently having a bad time with type casting while fetching some data.
Here is the data I have in the debug console:
(7, ["name": Doe, "id": 2042, "website": http://somedomaine.com/, "logo": http://somedomaine.com/img/, "category_id": 33, "category": Institutional partners, "order": 7])
I am sure this is really obvious, but I can't figure out how to access to data like name or id and it is giving me headache. This is what I have done:
let section = ( index as NSIndexPath ).section + 1 as Int
let row = ( index as NSIndexPath ).row as Int
let sectionContent = posts![ section ] as? Array< Any >
let entry = ( sectionContent?[ row ] as AnyObject )
After that, the best I can get is nil!
Here is a little more details: the posts variable is initiated at the top of the class like so:
internal var posts: [ Int: AnyObject ]?
The data are parsed like this (the original data come from a json feed which is fine):
func parsePosts( posts: [ Dictionary< String, AnyObject > ] ) -> ( [ Int: AnyObject ], Int ) {
var theCategories = [ Int : AnyObject ]()
var theSponsors = [ Int : AnyObject ]()
var theDict = [ Int : Array< Any > ]()
for item in posts {
let itemID = item[ "id" ] as! Int
let sponsorMeta = item[ "sponsor_meta" ]
let category = sponsorMeta?[ "category" ] as? String
let title = item[ "title" ]
let name = title?[ "rendered" ] as? String
if !( category ?? "" ).isEmpty {
let order = Int( ( sponsorMeta?[ "order" ] as? String )! )
let categoryID = sponsorMeta?[ "category_id" ] as! Int
let categoryOrder = sponsorMeta?[ "category_order" ] as! Int
let website = sponsorMeta?[ "url" ] as? String
let logo = sponsorMeta?[ "logo" ] as? [ String: Any ]
let logoSizes = logo?[ "sizes" ] as? [ String: Any ]
let imgUrl = logoSizes?[ "medium_large" ] as? String
let sponsor = [ "id": itemID, "name": ( name )! as String, "logo": imgUrl! as String, "website": ( website )! as String, "category": category!, "order": order!, "category_id": categoryID ] as [ String : Any ]
let category = [ "name": category!, "order": categoryOrder ] as [ String : Any ]
theCategories[ categoryID ] = category as AnyObject
theSponsors[ itemID ] = sponsor as AnyObject
}
}
for ( k, value ) in theCategories {
let categoryOrder = value[ "order" ] as! Int
var catDict = [ Int : [ String: AnyObject ] ]()
for ( _, element ) in theSponsors {
let sponsorCategoryID = element[ "category_id" ] as! Int
if sponsorCategoryID == k {
let sponsorOrder = element[ "order" ] as! Int
catDict[ sponsorOrder ] = element as? [ String : AnyObject ]
}
}
let sortedCat = catDict.sorted( by: { $0.0 < $1.0 } )
theDict[ categoryOrder ] = sortedCat
}
let sortedDict = theDict.sorted( by: { $0.0 < $1.0 } )
var finalDict = [ Int: AnyObject ]()
for ( t, v ) in sortedDict {
finalDict[ t ] = v as AnyObject?
}
return ( finalDict, theCategories.count )
}
I am sure it is just a small thing but I have been playing for hours with casting types and I haven't found a solution.
Does anybody have a suggestion? It will be much appreciated. Thanks!
I see that you have created a tuple and in order to access that data from that tuple I would suggest this approach
let posts = (7, dataDictioanry: ["name": "Doe", "id": 2042, "website": "http://somedomaine.com/", "logo": "http://somedomaine.com/img/", "category_id": 33, "category": "Institutional partners", "order": 7])
posts.dataDictioanry["name"]
I'm stuck with something appening when using lodash _.findWhere (the same with _.where)
var testdata = [
{
"id": "test1",
"arr": [{ "a" : "a" }]
},
{
"id": "test2",
"arr": []
}
];
_.findWhere(testdata, {arr : [] });
//--> both elements are found
I'm trying to extract elements from testdata where arr is an empty array, but _.where also includes elements with non-empty arrays.
I've also test with _.matchesProperty, but no way, same result.
I'm sure I'm missing something easy, but cannot see what :s
please help :)
http://plnkr.co/edit/DvmcsY0RFpccN2dEZtKn?p=preview
For this, you want to isEmpty():
var collection = [
{ id: 'test1', arr: [ { a : 'a' } ] },
{ id: 'test2', arr: [] }
];
_.find(collection, function(item) {
return _.isEmpty(item.arr);
});
// → { id: 'test2', arr: [] }
_.reject(collection, function(item) {
return _.isEmpty(item.arr);
});
// → [ { id: 'test1', arr: [ { a : 'a' } ] } ]
You can also use higher order functions, like flow(), so can abstract your callbacks:
var emptyArray = _.flow(_.property('arr'), _.isEmpty),
filledArray = _.negate(emptyArray);
_.filter(collection, emptyArray);
// → [ { id: 'test2', arr: [] } ]
_.filter(collection, filledArray);
// → [ { id: 'test1', arr: [ { a : 'a' } ] } ]