I'm trying to make autocomplete textbox using this link
https://github.com/devbridge/jQuery-Autocomplete
but I got this error
Uncaught TypeError: Cannot read property 'length' of undefined
this is my action method
public JsonResult GetNews(string prefix)
{
var newsList = NewsDataRoot.AutoCompleteTitle(prefix).Select(n => new
{
value = n.Title,
data = n.Id
}).ToList();
var myjson = Json(newsList, JsonRequestBehavior.AllowGet);
return myjson;
}
and it return this result when I test it in browser
[{"value":"this is a test","data":2006}]
I found the format must be
{
suggestions: [{
"value": "United Arab Emirates",
"data": "AE"
}, {
"value": "United Kingdom",
"data": "UK"
}, {
"value": "United States",
"data": "US"
}, {
"value": "United Funes",
"data": "DAN"
}]
}
how can do this?
thanks a lot!
also as you can see I tried transformResult but it doesnt worked
<script>
$('#autocomplete').autocomplete({
serviceUrl: '/TestAutoComplete/GetNews',
paramName: 'prefix',
transformResult: function(response) {
return {
suggestions: $.map(response.myData, function(dataItem) {
return { value: dataItem.valueField, data: dataItem.dataField };
})
};
},
onSelect: function (suggestion) {
alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
</script>
Try this, creates an anonymous object which just has the suggestions property
var newsList = NewsDataRoot.AutoCompleteTitle(prefix)
.Select(n => new {
value = n.Title,
data = n.Id
}).ToList();
var myjson = Json(new { suggestions = newsList }, JsonRequestBehavior.AllowGet);
if you want to set number to be numeric string you can try convert its value to string
public JsonResult GetNews(string prefix)
{
var newsList = NewsDataRoot.AutoCompleteTitle(prefix).Select(n => new
{
value = n.Title,
data = n.Id.ToString()
}).ToList();
var myjson = Json(new {suggestions = newsList}, JsonRequestBehavior.AllowGet);
return myjson;
}
Related
This question already has answers here:
Flutter: filter list as per some condition
(4 answers)
Closed 5 days ago.
Response from API:
"loan": [
{
"id": "612",
"icbsid": "55",
"loanId": "null",
"loanAcctNo": "001-063-06881-1",
"productId": "4",
"productName": "Fixed Principal+Int(Adv Pym)",
"approvedDate": "2017-11-13",
"loanAmount": "7359.97",
"loanBalance": "0.0",
"monthsToPay": "36",
"interestRate": "12.0",
"dueDate": "2020-12-13",
"status": "Closed",
"lastPayment": "2020-01-10"
},
{
"id": "4970",
"icbsid": "55",
"loanId": "16",
"loanAcctNo": "001-263-01625-4",
"productId": "6",
"productName": "Regular Long Term",
"approvedDate": "2022-01-27",
"loanAmount": "9934.21",
"loanBalance": "5384.21",
"monthsToPay": "60",
"interestRate": "0.0",
"dueDate": "2027-08-25",
"status": "Disbursed",
"lastPayment": "2022-12-29"
}
]
This is my code and it's working fine, but I need to filter the status
` #override
Future<List?> fetchLoanList() async {
final response = await httpServices.getRequest('mobileAppGetIcbsid?icbsid=001-0000055');
final jsonData = json.decode(response.data);
var map = Map<String, dynamic>.from(jsonData);
var userData = UserModel.fromJson(map);
// userData.loan?.where((element) => element.status == "Closed"); <-- not working for me
return userData.loan;
}`
I tried to uncomment this code userData.loan?.where((element) => element.status == "Closed"); it is working fine for displaying the data but not filtering the status. I am expecting to display only the data where status == 'Closed'
.where will create a new modified list but not modify the original list. Either reassign the original list or return the modified list. In this case I think 2 is better because we are only doing one filter operation to the list.
Also, .where will return Iterable which is the superclass of List. As your function is returning a List, we have to use .toList() to convert the Iterable to List.
Reassign the original list
final response = await httpServices.getRequest('mobileAppGetIcbsid?icbsid=001-0000055');
final jsonData = json.decode(response.data);
var map = Map<String, dynamic>.from(jsonData);
var userData = UserModel.fromJson(map);
// Reassign the result of .where to modifiedUserData
var modifiedUserData = userData.loan?.where((element) => element.status == "Closed");
return modifiedUserList.toList();
Return the modified list
final response = await httpServices.getRequest('mobileAppGetIcbsid?icbsid=001-0000055');
final jsonData = json.decode(response.data);
var map = Map<String, dynamic>.from(jsonData);
var userData = UserModel.fromJson(map);
// Return the result of .where directly
return userData.loan?.where((element) => element.status == "Closed").toList();
void test() {
var json =
'{"loan":[{"id":"1", "icbsid": "55","loanId": "null", "status": "Closed"},{"id":"2", "icbsid": "55","loanId": "null", "status": "None"},{"id":"3", "icbsid": "25","loanId": "sss", "status": "None"} ]}';
final jsonData = jsonDecode(json);
var map = Map<String, dynamic>.from(jsonData);
var data = UserModel.fromJson(map);
data.loan?.removeWhere((model) => model.status != 'Closed');
data.loan?.forEach((model) {
pr('id::${model.id} status::${model.status}');
});
}
class UserModel {
List<Loan>? loan;
UserModel(this.loan);
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
(json['loan'] as List<dynamic>?)?.map((e) => Loan.fromJson(e)).toList());
}
class Loan {
String? id;
String? status;
Loan(this.id, this.status);
factory Loan.fromJson(Map<String, dynamic> json) =>
Loan(json['id'], json['status']);
}
I have a problem converting the result of my object after saving it to the database, because I tried to follow the recommendations of https://jsonapi.org/ and convert my answers to the Json standard.
The implementation I did is not the best. This is:
async findAll() {
const data = new DataResponse<Product>();
return await this.repository.find().then(value => {
data.data = value;
data.isError = false;
data.message = "";
data.statusCode = 1;
return data;
}).catch(e => {
const error: HttpException = e;
data.data = [];
data.isError = true;
data.message = error.message;
data.statusCode = error.getStatus();
return data;
});
}
My json response I have this is:
{
"data": {
"id": 1,
"description": "Oreo",
"price": "6.5",
"category": "Oreo",
"stock": 50,
"createDate": "2021-10-28T14:11:47.454Z",
"lastUpdateDate": "2021-10-28T14:11:47.454Z"
},
"message": "",
"statusCode": 1,
"isError": false
}
why not to make a DTO or initalize and object of entity like new Product(),
and then assign values if you want to save them in Database rather than stringified JSON Objects?. this would resolve your problem.
I would like to extract the value from the JSON below (resReturn.result.gamingdata.original.success)
Just wonder why I can get the value only if I do several times of stringify and parse.
Can someone tell me how to simplify my code?
JSON:
{
"status":"Success",
"message":"100",
"resReturn":
{
"result":{
"gamingdata":
{
"headers":{},
"original":{"success":"Gaming Data Excel - upload success"},
"exception":null
}
}
}
}
My Code:
let resReturnJSON = JSON.stringify(this.UploadstatusGamingDataExcel.resReturn);
let resultobj = JSON.parse(resReturnJSON || '{}').result;
let resultJSON = JSON.stringify(resultobj);
let gamingdataobj = JSON.parse(resultJSON || '{}').gamingdata;
let gamingdataJSON = JSON.stringify(gamingdataobj);
let originalObj = JSON.parse(gamingdataJSON || '{}').original;
let originalJSON = JSON.stringify(originalObj);
let successObj = JSON.parse(originalJSON || '{}').success;
console.log(successObj);
const value = {
"status": "Success",
"message": "100",
"resReturn":
{
"result": {
"gamingdata":
{
"headers": {},
"original": { "success": "Gaming Data Excel - upload success" },
"exception": null
}
}
}
}
const jsonValue = JSON.stringify(value);
const valueFromJson = JSON.parse(jsonValue);
const success = (((((valueFromJson || {}).resReturn || {}).result || {}).gamingdata || {}).original || {}).success;
Check for truthiness for every property until you hit success property and return if found or return empty string.
const data = {
"status": "Success",
"message": "100",
"resReturn": {
"result": {
"gamingdata": {
"headers": {},
"original": {
"success": "Gaming Data Excel - upload success"
},
"exception": null
}
}
}
};
const success = (data.resReturn &&
data.resReturn.result &&
data.resReturn.result.gamingdata &&
data.resReturn.result.gamingdata.original.success) ?
data.resReturn.result.gamingdata.original.success : '';
console.log(success);
If you want a generalised function for json having array and objects, you can use this,
const data = {
"status": "Success",
"message": "100",
"resReturn": {
"result": {
"gamingdata": {
"headers": {},
"original": {
"success": "Gaming Data Excel - upload success"
},
"exception": null
}
}
}
};
const get = (p, o) =>
p.reduce((xs, x) =>
(xs && xs[x]) ? xs[x] : null, o)
console.log(get(['resReturn', 'result', 'gamingdata', 'original', 'success'], data));
I have one more simplest solution:
let obj: any;
try {
if (data.resReturn.result.gamingdata.original.success) {
obj = data.resReturn.result.gamingdata.original.success
}
} catch(e) {
obj = null
}
console.log(obj);
For other different ways, you can also refer this answer
I have a JSON response , Below is my response.
{
"data": [
{
"2": [
{
"name": "Test1",
"Address": "Test2"
},
]
},
{
"5": [
{
"name": "Test3",
"Address": "Test4"
},
]
},
]
}
I am able to access till data from the response.Here "2" and "5" are date.If one date is present in this json response then for that response i have to get name and address
But I have to show list of data.
<div *ngFor = "let data of result">
<span>{{data.name}}</span>
<span>{{data.Address}}</span>
</div>
In ts file,
let result = response.data;
I want to access name and address from this.Can anyone please help me how to do this.
You can use Object.key, map and concat function to flat your data like this
let obj = this.result;
this.result = Object.keys(obj).map(function (key) {
let objkey = obj[key];
let first = Object.keys(objkey)[0]
return obj[key][first];
});
this.result = [].concat.apply([], this.result);
Demo at https://stackblitz.com/edit/angular-flat-array-property
Updated:
I update demo with filter to apply your filter by date.
let obj = this.result;
var filter = '5';
this.result = Object.keys(obj).map(function (key) {
let objkey = obj[key];
let first = Object.keys(objkey)[0]
if(filter == first){
return obj[key][first];
}else{
return null;
}
});
this.result = [].concat.apply([], this.result.filter(c=>c != null));
I'm trying to extract only sub document from an array has the following schema :
const UserSchema = Schema({
name: {
type: String
},library:[{
story:{type: Schema.Types.ObjectId,ref: 'Story'}
}],
});
i tried to use :
module.exports.getUserStories = function(userId, callback){
User.findOne({_id: userId },callback)
.select('library.story')
};
and it gives this result :
{
"_id": "5949615072e15d2b34fa8f9d",
"library": [
{
"story": "592ae46cf2a0ba2b208cb092"
},
{
"story": "592ae608df26d80790092fe9"
},
{
"story": "592ae46cf2a0ba2b208cb092"
}
]
}
but what i'm expecting to get is only this :
[
{
"story": "592ae46cf2a0ba2b208cb092"
},
{
"story": "592ae608df26d80790092fe9"
},
{
"story": "592ae46cf2a0ba2b208cb092"
}
]
I already tried to use double selection like :
module.exports.getUserStories = function(userId, callback){
User.findOne({_id: userId },callback)
.select('library.story')
.select('story')
};
But is gives the same result
Try this one :
module.exports.getUserStories = function(userId, callback){
User.find({_id: userId },{'library.story'}).then(function(user){
if(user){
callback(user.library);
}});
};
Docs here
This output is expected to return by "select" but simply you can prepare the returned data to be as you need as following:
User.findOne({_id: userId }).select('library').then(function(result){
if(result){
//If there is returned item
var stories = result.library;
//Continue ...
}
},function(error){
//Error handling
})