I am trying to append array elements to the list using below code:
function GetList() {
let list = [];
$.ajax({
url: '../Lookup/GetList',
type: 'GET',
cache: true,
dataType: "json",
success: function (response) {
debugger;
list = response;
//for (var data in response) {
// list = { value: data, rest: list };
//}
//for (let i = response.length - 1; i >= 0; i--) {
// list = { value: array[i], rest: list };
//}
//for (let i = response.length - 1; i >= 0; i--) {
// list.push(response[i]);
//}
}
});
return list;
}
I have attached the screenshot of array data format. I need in the below list format:
var list= [
{
"id": "1",
"LookupMasterName": " Source1",
"Description": "xxx",
"Enabled Flag":"Y"
},
{
"id": "2",
"LookupMasterName": " Source2",
"Description": "yyy",
"Enabled Flag": "Y"
}
];
Above code doesn't work. It returns empty list. Can you help?
CodePudding user response:
If you are trying to reverse the array you could just do
let array = [1,2,3,4]
let list = array.reverse()
console.log(list)
So here array as well as list will be [4,3,2,1]
CodePudding user response:
It's returning an empty list because this line return list;
is executed before Ajax is completed. A solution to fix it is wrapping your Ajax request into a Promise:
Example:
function GetList() {
let list = [];
return new Promise((resolve) => {
$.ajax({
url: "../Lookup/GetList",
type: "GET",
cache: true,
dataType: "json",
success: function (response) {
list = response;
resolve(list);
},
});
});
}
Then calling GetList
:
GetList().then(list => /* do whatever you need */)