How to add or remove rest api array list data - list

I wanna add some data or string to an array list strings in my rest api data, an it's not working.
I don't know why.
Here is my api data which i got from my api in my local server the json data is below here.
"hotels": [ {
"image": "http://0.0.0.0:8080/uploads/users/IWpEqUWxUxbWsmIoYfUX/95024057775943965869.jpg",
"bedPrice": "10",
"roomPrice": "30",
"rooms": "50",
"ac": "yes",
"address": "kaambo",
"latitude": "43.0890",
"laundry": "yes",
"name": "jaabir",
"location": "Bosaso",
"details": "Hosbitaalka Sixa Garoowe waxa ka howlgali doona 23/06/2022 Dr. Ahmed Bashe (abu-shafi) (FCPS MRCS-UK) oo ka socda Hosbitalka Shaafi Muqdisho kuna takhasusay qalliimada LAPAROSCOPY-ga sida Xameetida,Uur-kujirta,Eernada,Burooyinka IWM. Dr-ku wuxuu si joogta ah u imanayaa bil kasta insha allah. Wac: 7747373, 5065444, 5065333.Hosbitaalka Sixa Garoowe waxa ka howlgali doona 23/06/2022 Dr. Ahmed Bashe (abu-shafi) (FCPS MRCS-UK) oo ka socda Hosbitalka Shaafi Muqdisho kuna takhasusay qalliimada LAPAROSCOPY-ga sida Xameetida,Uur-kujirta,Eernada,Burooyinka IWM. Dr-ku wuxuu si joogta ah u imanayaa bil kasta insha allah. Wac: 7747373, 5065444, 5065333.Hosbitaalka Sixa Garoowe waxa ka howlgali doona 23/06/2022 Dr. Ahmed Bashe (abu-shafi) (FCPS MRCS-UK) oo ka socda Hosbitalka Shaafi Muqdisho kuna takhasusay qalliimada LAPAROSCOPY-ga sida Xameetida,Uur-kujirta,Eernada,Burooyinka IWM. Dr-ku wuxuu si joogta ah u imanayaa bil kasta insha allah. Wac: 7747373, 5065444, 5065333.",
"id": "456",
"beds": "100",
"internet": "yes",
"fastfood": "yes",
"longitude": "23.0890",
"images": [
"http://0.0.0.0:8080/uploads/users/IWpEqUWxUxbWsmIoYfUX/95024057775943965869.jpg",
"http://0.0.0.0:8080/uploads/users/IWpEqUWxUxbWsmIoYfUX/95024057775943965869.jpg",
"http://0.0.0.0:8080/uploads/users/IWpEqUWxUxbWsmIoYfUX/95024057775943965869.jpg"
],
"likedUsers": [
"HftAroebyiUhaKSmsyrc"
],
"adress": "laanta hawada"
}
]
And here is dart code.
_likeUser()async{
String api = "http://0.0.0.0:8080/path=hotels/456";
// this list from previous page _data['likedUsers'].toList();
List<String> likes = widget.likedUsers as List<String>;
if(widget.likedUser.contain(widget.currentUser){
setState((){ _isLiked = false;});
var likeRemoved = likes.remove(widget.currentUser);
await http.patch(Uri.parse(api), body: json.encode(<String, Object>{
"likedUsers": [likeRemoved]
});
}else{
var likeAdded = likes.add(widget.currentUser);
await http.patch(Uri.parse(api), body: json.encode(<String, Object>{
"likedUsers": [likeAdded]
});
setState((){
_isLiked = true;
});
}
}

The solution is here
_likeUser()async{
String api = "http://0.0.0.0:8080/path=hotels/456";
// this list from previous page _data['likedUsers'].toList();
var likes = widget.likedUsers;
if(widget.likedUser.contain(widget.currentUser){
// i removed item to list in this here
var remove = likes.remove(widget.currentUser);
setState((){ _isLiked = false;});
await http.patch(Uri.parse(api), body: json.encode(<String, Object>{
"likedUsers": likes,
});
}else{
// i added item to list in this here
var add = likes.add(widget.currentUser);
await http.patch(Uri.parse(api), body: json.encode(<String, Object>{
"likedUsers": likes,
});
setState((){
_isLiked = true;
});
}
}

Related

How to extract values from JSON response in Postman?

I have a JSON Response :
[{
"dateTime": 1603650600000,
"supplierName": "Mr Orange GP ",
"gender": "male",
"supplierId": "788",
"appointmentId": 454687,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}, {
"dateTime": 1603650600000,
"supplierName": "Mr Kennedy test ",
"gender": "male",
"supplierId": "600",
"appointmentId": 573993,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}, {
"dateTime": 1603651500000,
"supplierName": "Mr Orange GP ",
"gender": "male",
"supplierId": "788",
"appointmentId": 454688,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}, {
"dateTime": 1603651500000,
"supplierName": "Mr Kennedy test ",
"gender": "male",
"supplierId": "600",
"appointmentId": 573994,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}]
I need to extract the values of first occurrence of dateTime, AppointmentId and tentativeAppointmentCode.
Tried below mentioned code but didn't work in this case.
var jsonData=JSON.parse(responseBody);
postman.setEnvironmentVariable("dateTime",jsonData.dateTime);
How can I extract these values and store in a variable so that I can use it in other requests?
Assuming, by "reservation ID" you mean tentativeAppointmentCode (reservation ID doesn't occur in your response body), the following will do it:
let jsonData = pm.response.json();
pm.environment.set("dateTime",jsonData[0].dateTime);
pm.environment.set("appointmentId",jsonData[0].appointmentId);
pm.environment.set("tentativeAppointmentCode",jsonData[0].tentativeAppointmentCode);
I have done something like this for storing a token for later use
const jsonData = pm.response.json();
pm.environment.set("token", jsonData.access_token);

Dart - find duplicate values on a List

how can I find duplicate values on a list,
Let's say I got a List like this:
List<Map<String, dynamic>> users = [
{ "name": 'John', 'age': 18 },
{ "name": 'Jane', 'age': 21 },
{ "name": 'Mary', 'age': 23 },
{ "name": 'Mary', 'age': 27 },
];
How I can iterate the list to know if there are users with the same name?
A simple way would be this:
void main() {
List<Map<String, dynamic>> users = [
{ "name": 'John', 'age': 18 },
{ "name": 'Jane', 'age': 21 },
{ "name": 'Mary', 'age': 23 },
{ "name": 'Mary', 'age': 27 },
];
List names = []; // List();
users.forEach((u){
if (names.contains(u["name"])) print("duplicate ${u["name"]}");
else names.add(u["name"]);
});
}
Result:
duplicate Mary
Probably a cleaner solution with extensions.
By declaring:
extension ListExtensions<E> on List<E> {
List<E> removeAll(Iterable<E> allToRemove) {
if (allToRemove == null) {
return this;
} else {
allToRemove.forEach((element) {
this.remove(element);
});
return this;
}
}
List<E> getDupes() {
List<E> dupes = List.from(this);
dupes.removeAll(this.toSet().toList());
return dupes;
}
}
then you can find your duplicates by calling List.getDupes()
Note that the function removeAll doesn't exist in my current Dart library, in case you're reading this when they implement it somehow.
Also keep in mind the equals() function. In a List<String>, ["Rafa", "rafa"] doesn't contain duplicates.
If you indeed want to achieve this level of refinement, you'd have to apply a distinctBy function:
extension ListExtensions<E> on List<E> {
List<E> removeAll(Iterable<E> allToRemove) {
if (allToRemove == null) {
return this;
} else {
allToRemove.forEach((element) {
this.remove(element);
});
return this;
}
}
List<E> distinctBy(predicate(E selector)) {
HashSet set = HashSet();
List<E> list = [];
toList().forEach((e) {
dynamic key = predicate(e);
if (set.add(key)) {
list.add(e);
}
});
return list;
}
List<E> getDupes({E Function(E) distinctBy}) {
List<E> dupes = List.from(this);
if (distinctBy == null) {
dupes.removeAll(this.toSet().toList());
} else {
dupes.removeAll(this.distinctBy(distinctBy).toSet().toList());
}
return dupes;
}
}
I had a feeling Rafael's answer had code similar to Kotlin so I dug around and saw that these functions are part of the kt_dart library which basically gets the Kotlin standard library and ports it to Dart.
I come from a Kotlin background so I use this package often. If you use it, you can simply make the extension this much shorter:
extension KtListExtensions<T> on KtList<T> {
KtList<T> get duplicates => toMutableList()..removeAll(toSet().toList());
}
just make sure to add kt_dart on your pubspec: kt_dart: ^0.8.0
Example
final list = ['apples', 'oranges', 'bananas', 'apples'].toImmutableList();
final duplicates = list.duplicates; // should be ['apples'] in the form of an ImmutableList<String>
void main() {
List<String> country = [
"Nepal",
"Nepal",
"USA",
"Canada",
"Canada",
"China",
"Russia",
];
List DupCountry = [];
country.forEach((dup){
if(DupCountry.contains(dup)){
print("Duplicate in List= ${dup}");
}
else{
DupCountry.add(dup);
}
});
}

Access a list item stored in key value pair inside a list of map

I am using flutter/dart and I have run into following problem.
I have a list of map like this.
var questions = [
{
'questionText': 'What\'s your favorite color?',
'answer': ['Black', 'Red', 'Green', 'White']
},
{
'questionText': 'What\'s your favorite animal?',
'answer': ['Deer', 'Tiger', 'Lion', 'Bear']
},
{
'questionText': 'What\'s your favorite movie?',
'answer': ['Die Hard', 'Due Date', 'Deep Rising', 'Dead or Alive']
},
];
Now suppose I need to get the string Tiger from this list. How do I do that? Dart is seeing this as List<Map<String, Object>> questions
Maybe a more portable way with a function:
String getAnswer(int question, int answer) {
return (questions[question]['answer'] as List<String>)[answer];
}
// Get 'Tiger'
String a = getAnswer(1, 1);
You can convert object in list in following way and then use index to get any value.
var p = questions[1]['answer'] as List<String>;
print(p[1]);

DynamoDB overriding existing key value pair due to AttributeValues

----------------- GIVING MORE CONCRETE EXAMPLES BELOW -----------------
I have the following function, where I take user, name, sex from parameters and update the existing client for that user.
function createRecord(user, personName, sex) {
var sexPayload = [];
var dynamoParams = {
TableName: 'account',
Key: {
id: user
},
UpdateExpression: "set #client.#person.#sex = :sexPayload",
ExpressionAttributeNames: {
"#client": "client",
"#person": personName,
"#sex": sex
},
ExpressionAttributeValues: {
":sexPayload": sexPayload,
},
ConditionalExpression: "attribute_not_exists(#client.#person.#sex)"
};
docClient.update(dynamoParams, function(err, data){
something...
});
}
if personName = "John" sex = "man",
this creates
client: {
John: {"M": {"man": {"L": []}}},
}
and when I pass in another name = "John" sex = "female",
this overrides existing John "man" and writes "female" under John
client: {
John: {"M": {"female": {"L": []}}},
}
What I want to achieve is this:
client: {
John: {"M": {"man": {"L": []}, {"female": {"L": []}},
}
what am I doing wrong??

google maps geocoding not marking all places on the map

below is the code ,there is an array which contains names of 62 places,but while geocoding not all 62 places are getting marked on the map,only very few places are getting marked on map.
function createMarker(latlng){
var marker = new google.maps.Marker({
position: latlng,
map: map
});
var markers = ["chennai", "Kashmir", "Russia", "Jalandhar", "Netherlands", "Koregaon Park", "Piparia", "South Africa", "USA", "Siliguri", "Dhule", "United Kingdom", "Shendra", "Baramulla", "Haridwar", "New Delhi", "United Arab Emirates", "Ladakh", "Noida", "Shanghai", "Gurgaon", "Rajouri", "Netherlands", "Ranchi", "Abruzzo", "Waluj", "Ho Chi Minh", "Germany", "Bhopal", "Soenderborg", "Delhi", "Dindori", "Brazil", "Magarpatta", "Chennai", "Taiwan", "Jharsuguda", "Rakholi", "Turkey", "Denmark", "Bangalore", "Selangor", "Rajgarh", "Vardhaman Industrial Estate", "Sagar", "Jammu", "Beijing", "Jamshedpur", "Jabalpur", "SIDCUL", "Hyderabad", "PTB Rakholi", "Haimen", "Ahmedabad", "OFC Rakholi", "Mumbai", "Bafliaz", "Srinagar", "Argentina", "Dadra", "Mexico", "Tiruchirappalli"]
var map;
function initializeMaps(eventObject)
{
map = new google.maps.Map(document.getElementById('googlemap1'), {
zoom: 5,
center: new google.maps.LatLng(21.0000,78.0000),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var geocoder = new google.maps.Geocoder();
var marker, i;
for (i = 0; i < markers.length; i++) {
geocodeAddress(markers[i]);
}
}
function geocodeAddress(location) {
var geocoder= new google.maps.Geocoder();
geocoder.geocode( { 'address': location}, function(results, status) {
// alert(status);
if (status == google.maps.GeocoderStatus.OK) {
// alert(results[0].geometry.location);
// map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location,location);
}
else
{
alert("some problem in geocode" + status);
}
});
}
function createMarker(latlng){
var marker = new google.maps.Marker({
position: latlng,
map: map
});
hi i found a work around to mark all the places.at a time google geocodes only 11 requests,so i added a delay between every iteration and since there was delay between each hit to the geocoding server,geocoding was possible for all the places in the array.
for(i = 1; i < markers.length; i++){
(function(i){
setTimeout(function(){
geocodeAddress(markers[i]);
}, 1000 * i);
}(i));
}