fetch the associative array particular value with its key name - javascript

i have a function . here i am passing an array applicationTabId = {"twitter": "15", "dropbox": "14"}; "}; I have an ajax success function .In this the variable appName name holds the key names as twitter , dropbox etc. I got this from database as ajax response. i want to find the value associated with this from the array. variable appName holding the key names and iam getting it from database as ajax response. i need to check the corresponding value of this name from array.
function getapplicationlogouturl(applicationTabId) {
chrome.storage.sync.get("endpoint", function (obj) {
FetchLogoutUrl = {
"applicationName": applicationTabId,
"sdcode": sdcode,
"type": "Chrome Fetch Application Logout Url"
};
$.ajax({
type: "POST",
url: obj.endpoint,
dataType: "json",
data: JSON.stringify(FetchLogoutUrl),
context: document.body,
timeout: globalTimeout,
success: function (response) {
if (response != null ) {
for (var i = 0; i < response.length; i++) {
var appName = response[i].name;
console.log(applicationTabId);
// o/p as {"twitter": "15", "dropbox": "14"}
console.log(appName);
//o/p as twitter
//dropbox
var tabid = applicationTabId.appName;
//var tabid = applicationTabId[appName];
console.log(tabid);
//o/p as undefined
console.log(appName+'---'+tabid);
if (appName in applicationTabId){
}
}
}
},
});
});
}

Apply loop like below:
$.each(applicationTabId, function(key,value){
console.log(key);
console.log(value);
});
Based on code you provided now, change your code like below:
function getapplicationlogouturl(applicationTabId) {
FetchLogoutUrl = {
"applicationName": applicationTabId,
};
$.ajax({
type: "POST",
url: obj.endpoint,
dataType: "json",
data: JSON.stringify(FetchLogoutUrl),
context: document.body,
success: function (response) {
if (response != null ) {
for (var i = 0; i < response.length; i++) {
var appName = response[i].name;
var tabid = applicationTabId[appName];
//print key value data in console to check working fine
console.log(appName+'---'+tabid);
}
}
},
});
}
Note:- var appName and var tabid value will be changed after each iteration happen.

Related

Get JSON array data by field name

I'm trying to get JSON data by field name like this data.name and it return the desired data, but I have 25 fields in the array and I want to make this dynamically, using data + "." + variable, when I alert it returns [Object object].name, so how I can make it executable?
I tried many ways but all failed, please help me doing this.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: {
'Arrnagement': Arrnagement
},
success: function(data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = data[0].jid;
alert(resulting);
if (result[i].innerHTML = data[0].jid != "undefined") {
result[i].innerHTML = data[0].jid;
} else {
result[i].innerHTML = "";
}
}
//jid = name;
//data[0].name returns "Joun"
//data[0]+"."+jid returns [object object].name but i need it to return "Joun"
This should work. I changed the dot notation while accessing the object property.
$.ajax({
type: "Get",
url: "/Home/Report_Data",
datatype: "json",
dataSrc: "",
contentType: 'application/json; charset=utf-8',
data: { 'Arrnagement': Arrnagement },
success: function (data) {
var result = getElementsById("LD_name LD_Loan_Type LD_id LD_Full_Name_AR LD_GENDER LD_BIRTH_INCORP_DATE LD_PS_MOTHER_NAME LD_Street_AR LD_TEL_MOBILE LD_EMPLOY_STATUS_D LD_EMPLYRS_Name LD_MARITAL_STATUS LD_PS_PL_OF_BIR_AR LD_wifeName LD_Effective_Interest_Rate LD_Contract_amount LD_Repayment_Amount LD_Sector_name LD_NUM_REPAYMENTS LD_Loan_Maturity LD_Orig_Contract_Date LD_Loan_CCY LD_Arrangement LD_COLLATERAL_TYPE LD_Description LD_COLLATERAL_VALUE LD_COLLATERAL_Currency LD_GUARANTOR_ID LD_NATIONALITY LD_G_Full_Name_En LD_G_DATE_OF_BIRTH LD_G_PLACE_OF_BIRTH LD_G_MOTHER_NAME_EN LD_HOUSING_LOAN_AREA_CLASS LD_HOUSING_PROPERTY_NATURE LD_HOUSING_LOAN_PURPOSE LD_HOUSING_PROPERTY_AREA");
var responseData = data[0];
var jid;
for (var i = 0; i < result.length; i++) {
jid = (result[i].id.substring(3));
var resulting = responseData[jid];
alert(resulting);
if (responseData[jid]) {
result[i].innerHTML = responseData[jid];
}
else {
result[i].innerHTML = "";
}
}
Try giving data[0][jid], we can give a variable in brackets also inorder to get the data
Hope it works
If do foo.bar you are getting a property with the name 'bar' on object foo. If you have some variable const bar = "qux" and you want to access property on some object with the same name as bar value /"qux"/ you just need to use square brackets - foo [bar], which will be the same as calling foo.qux; So, in your case you just need to use data[0][jid] instead of data [0].jid, supposing jid contains a string that is also a key in data[0].
You can just do data[0][variableName] and this will return the data you want. for example. If data had a json string [{ "Name" : "Jane Doe"}] You could execute it like this.
var variableName = "Name";
console.log(data[0][variableName])
This would return "Jane Doe".
if you have your field names in an array you can loop through them using $.each or a for loop.
For example say your json string is [{"First_Name" : "Jane", "Last_Name" : "Doe", "Age" : 32}] you could get all the values from the json string doing this.
var FieldNames = ["First_Name" , "Last_Name", "Age"]
$.each(FieldNames, function(i,item) {
console.log(data[0][item])
}
OR
var FieldNames = ["First_Name" , "Last_Name", "Age"]
for(var i = 0; i < FieldNames.length; i++) {
console.log(data[0][FieldNames[i]])
}

Delete key/value pair from json array obtained from ajax response if key is found

I am fetching data from one list in sharepoint and storing it in json array to pass it onto another function to create a new item in Sharepoint list.The first function is:
$.ajax({
url: someSharepointListUrl,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var array = new Array();
for (var i=0; i< data.d.results.length; i++) {
var it=data.d.results[i];
array.push({
AllLinks: it.AllLinks,
LinkURL: it.LinkURL.Url
});
}
dataCharts=JSON.stringify(array);
alert(dataCharts);
AddDefaultLinks(dataCharts);
},
error: function (data) {
alert(data.responseJSON.error);
}
});
The item is stored in the list as as:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
The second function which fetches data from list after item is created is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var c = [];
var stringData = JSON.stringify(data.d.results[0].AllLinks);
//alert(stringData);
c.push(JSON.parse(stringData));
alert(c);
var xonly = c.filter(function (entry){
return entry.AllLinks != x;
});
alert(xonly);
},
error: function() {
alert('fail');
}
});
I need to match if a value exists in this newly created list Item.If yes then delete it eg Lin.
value of c(json array) here is:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
`
entry.AllLinks doesnt filter data here.AllLinks is undefined in entry.AllLinks.Please help
Use Array.findIndex() to find the desired value inside array, and use Array.splice() method to remove that object.

Cannot read property of undefined after JSON parse

I have done an ajax request in my code and it works good. After that I want to extract only the necessary info and re-post it to another script. Until now here is my code:
$.ajax({
type: "POST",
url: url,
data: {xhr_id: xhr_id},
success: function (jsondata) {
var product_data = [];
for (var i = 0; i <= 3; i++) {
//alert(jsondata.products[i].product_description.toSource());
product_data[i] = {};
product_data[i]["product" + i] = jsondata.products[i].product_description;
//alert(product_data[i]["product" + i].toSource());
}
},
dataType: "json"
});
The problem is that both the alerts work fine, displaying the information I want. However, I get an error message of "Uncaught TypeError: Cannot read property 'product_description' of undefined" which breaks the script and prevents me from doing anything else. What am I doing wrong, any ideas?
'product_description' of undefined" what it means is that your are trying to access property on undefined variable. That implies "jsondata.products[i]" resulted in undefined value which have occured due to index out of range.How many records are returned in jsondata 3 or 4,check and adjust the condition in for loop
The parameter in the success() function of $.ajax is a string. You have to put it through a parse function to make json. See your code below modified but not tested.
$.ajax({
type: "POST",
url: url,
data: {xhr_id: xhr_id},
success: function (jsondata) {
var oData;
try { oData=jQuery.parseJSON(jsondata) }
catch(err) {
alert("Problem parsing json string : " + jsondata)
return false
}
var product_data = [];
for (var i = 0; i <= 3; i++) {
//alert(oData.products[i].product_description.toSource());
product_data[i] = {};
product_data[i]["product" + i] = oData.products[i].product_description;
//alert(product_data[i]["product" + i].toSource());
}
},
dataType: "json"
});

jQuery autocomplete multiple fields

I have the below AJAX response which is an object containing a food item and price.
{
"pizza": "100.00",
"Burger": "45.00",
"Ice Cream": "25.00",
"Chips": "20.00",
"Peanut Butter": "50.00"
}
I'm trying to build a form wherein the user enters an item and the 'price' input field gets automatically filled. I went through the jQuery documentation and I'm confused as to how I can get the Item inputbox to only look for the 'food' items (or keys) in the array.
I'm getting a this.source is not a function in my console. I'm aware of the reason where I'm going wrong (I believe its due to the fact that they keys are different food items as opposed to 'label').
Here is my js
$(document).ready(function(){
var myItems = getData();
$('#Item').autocomplete({
source: myItems,
focus: function(event,ui){
$('#Item').val(ui.item.Item);
return false;
},
select : function(event,ui){
$('#Rate').val(ui.item.Price);
}
});
});
function getData(){
var myItems = {};
$.ajax({
type : 'GET',
async: false,
url : 'http://127.0.0.1:8000',
data : {},
contentType: "application/json",
crossDomain:true,
success : function(json){
for(i = 0; i <json.length; i++){
myItems[json[i].Item] = json[i].Price;
//below doesn't work in loop
// myItems['Item'] = json[i].Item;
// myItems['Price'] = json[i].Price;
}
},
error : function(response){
console.log('error')
}
});
// console.log('Is this working '+ myItems);
console.log(myItems);
return myItems;
};
Please let me know how I can solve this issue.
The source option when you create the autocomplete needs to be either an Array of strings with the values, a String for a url with a JSON response that holds the values or a function callback which takes a pair of request and response parameters.
The way you have assigned var myItems = getData(); means the myItems is not one of these types. It will currently be an empty object because it is assigned before your Ajax call will complete.
Assuming you only need to load the data once, create the autocomplete in the success callback for your Ajax request;
$(document).ready(function(){
getData();
function getData(){
$.ajax({
type : 'GET',
async: false,
url : 'http://127.0.0.1:8000',
data : {},
contentType: "application/json",
crossDomain:true,
success : function(json){
var myItems = {};
for(i = 0; i < json.length; i++){
myItems[json[i].Item] = json[i].Price;
}
$('#Item').autocomplete({
source: myItems,
focus: function(event,ui){
$('#Item').val(ui.item.Item);
return false;
},
select : function(event,ui){
$('#Rate').val(ui.item.Price);
}
});
},
error : function(response){
console.log('error')
}
});
};
});
I actually tried going about this another way. i managed to pull all keys into a single array and use that as the source. the second box gets filled based on the value of the first box on the select event.
$(document).ready(function(){
var myItems = getData();
var keys = [];
for(var k in myItems){
keys.push(k);
}
$('#Item').autocomplete({
source: keys,
select : function(e,ui){
var value = myItems[ui.item.value];
$('#Rate').val(value);
}
});
});
function getData(){
var myItems = {};
$.ajax({
type : 'GET',
async: false,
url : 'http://127.0.0.1:8000',
data : {},
contentType: "application/json",
crossDomain:true,
success : function(json){
for(i = 0; i <json.length; i++){
myItems[json[i].Item] = json[i].Price;
}
},
error : function(response){
console.log('error')
}
});
// console.log(myItems);
return myItems;
};

jQuery Ajax call in loop losing local variable reference

I am making several jQuery ajax calls within a loop. Each time one of the ajax calls return I need to reference a value corresponding to the original ajax call. My current code doesn't work properly, in that the value of the lskey variable has been altered by further loop iterations.
Here is the code:
for (var i = 0, len = localStorage.length; i < len; i++) {
var lskey = localStorage.key(i);
if (lskey.substr(0, 4) === 'form') {
var postdata = localStorage.getItem(lskey); // Get the form data
$.ajax({
type: "POST",
async: "false",
url: "/Profile/PostForm",
data: postdata,
success: function (data) {
$('#rollinginfo').append('<br>' + data + ',key=' + lskey);
localStorage.removeItem(lskey); // Remove the relevant localStorage entry
}
, error: function (data) { $('#rollinginfo').append('<br />ERR:' + data); }
});
}
}
The problem is that lskey is being altered each time the loop executes, and therefore the success callback does not have a reference to the value of lskey that existed at the time of the call.
How do I reference the correct value of lskey for each success callback?
for (var i = 0, len = localStorage.length; i < len; i++) {
var lskey = localStorage.key(i);
if (lskey.substr(0, 4) === 'form') {
var postdata = localStorage.getItem(lskey); // Get the form data
$.ajax({
type: "POST",
async: "false",
url: "/Profile/PostForm",
data: postdata,
local_lskey: lskey
success: function (data) {
$('#rollinginfo').append('<br>' + data + ',key=' + lskey);
localStorage.removeItem(this.local_lskey); // Remove the relevant localStorage entry
}
, error: function (data) { $('#rollinginfo').append('<br />ERR:' + data); }
});
}
}
This should work.
In the end I added the key info to the server posting, and then returned it from the server in JSON format so the success function could then simply refer to the key contained in the server response.
Have you considered chaining the AJAX calls? Basically you can make one AJAX call, process the result, modify lskey, etc. Then when you are ready, increment i and issue the second AJAX call. Loop this way instead of using the for loop...
You could put your ajax call into its own function and pass the lskey and postData values in. That way localStorage.removeItem(lskey) will refer to the lskey variable in the context of the function rather than the context of the loop.
Example
Declare the function -
function postForm(postdata, lskey) {
$.ajax({
type: "POST",
async: "false",
url: "/Profile/PostForm",
data: postdata,
success: function(data) {
$('#rollinginfo').append('<br>' + data + ',key=' + lskey);
localStorage.removeItem(lskey); // Remove the relevant localStorage entry
},
error: function(data) {
$('#rollinginfo').append('<br />ERR:' + data);
}
});
}
Then you can call your function from your loop -
for (var i = 0, len = localStorage.length; i < len; i++) {
var lskey = localStorage.key(i);
if (lskey.substr(0, 4) === 'form') {
var postdata = localStorage.getItem(lskey); // Get the form data
postForm(postdata, lskey);
}
}
You could also declare the function just before the loop (assigning it to a variable) and then call it within the loop.
var postForm = function(postdata, lskey) {
$.ajax({
type: "POST",
async: "false",
url: "/Profile/PostForm",
data: postdata,
success: function(data) {
$('#rollinginfo').append('<br>' + data + ',key=' + lskey);
localStorage.removeItem(lskey); // Remove the relevant localStorage entry
},
error: function(data) {
$('#rollinginfo').append('<br />ERR:' + data);
}
});
}
for (var i = 0, len = localStorage.length; i < len; i++) {
var lskey = localStorage.key(i);
if (lskey.substr(0, 4) === 'form') {
var postdata = localStorage.getItem(lskey); // Get the form data
postForm(postdata, lskey);
}
}

Categories

Resources