Get JSON array data by field name - javascript

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]])
}

Related

fetch the associative array particular value with its key name

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.

DataSet Value in Jquery C#

I have one page in which, URL contains Querystring Value.
QSecID=164&QTempId=55&QSecName=New%20Temp%20Bt
When the page loads them and tries to get the value it works fine.
$(document).ready(function() {
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
var urlName = getUrlParameter('QSecName');
alert(urlName);
getImageData(urlName); //Pass Query String Value to Function
});
Now I am passing this value to C#, ASPX.CS page and try to fetch the data based on QSecName.
But i got error. Here is my Jquery function.
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
//data: '',
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("Success");
alert(JSON.parse(data.d));
}
});
}
My C# Page returns the DataSet in Jquery.
[WebMethod()]
public static string GetImageData(string dataSecName)
//public static string GetRole()
{
clsSection objSectNew = new clsSection();
DataSet DS = new DataSet();
DS = objSectNew.GetImageDataByJQ(dataSecName);
return JsonConvert.SerializeObject(DS);
}
Edit Code 1
Here is my SQL Statement Which is get executed when i run the page and
DS = objSectNew.GetImageDataByJQ(dataSecName);
this method pass the query string value in to execute the Stored Procedure.
select mhp.ImageName,mhp.HotSpotID,imgdetail.XCordinate,imgdetail.YCordinate
from tbl_SOAPDetailsInfo e inner join M_ImageHotSpot mhp on e.ImgHotSpotName=mhp.ImgHotSpotNameByUser
inner join M_ImageHotSpotDetail imgdetail on mhp.HotSpotID=imgdetail.HotspotIDFK where e.SOAP_D_Name='New Temp Bt'
I want to use my XCordinate, YCordinate and ImageName to display image using jquery. but Inside the alert BOX
**[object] [object]**
error display. How can i get and assign this value X AND Y value and display in DIV.
Edit Code 2
ImageName XCordinate YCordinate
$parent in angularjs.png 1146 590
$parent in angularjs.png 1216 588
$parent in angularjs.png 1188 626
$parent in angularjs.png 1162 582
$parent in angularjs.png 1193 586
The Database Value. JSON FORMAT DATA
{"d":"{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"}
So as per your question [object] [object] is not an error. It means you cannot fetch it in a correct manner.
Though I am not sure what kind of data you are sending from your back-end code in data But you could try following way,
var data = "{\"Table\":[{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1146\",\"YCordinate\":\"590\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1216\",\"YCordinate\":\"588\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1188\",\"YCordinate\":\"626\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1162\",\"YCordinate\":\"582\"},{\"ImageName\":\"$parent in angularjs.png\",\"ImagePath\":\"~/Administration/imageHotspot/$parent in angularjs.png\",\"HotSpotID\":11,\"XCordinate\":\"1193\",\"YCordinate\":\"586\"}]}"
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
So now if you replace your code with above sample your code should look like below:
function getImageData(name) {
// alert(nextDay);
$.ajax({
type: "POST",
url: "Section.aspx/GetImageData",
data: JSON.stringify({
"dataSecName": name
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
console.log(obj.Table);
var tableObj = obj.Table
console.log(obj.Table);
var arrayLength = tableObj.length;
for (var i = 0; i < arrayLength; i++) {
console.log(tableObj[i].ImageName);
console.log(tableObj[i].XCordinate);
console.log(tableObj[i].YCordinate);
alert(tableObj[i].YCordinate);
}
});
}
Note : Try to debug in browser console you would understand object notation more details.
See the screen shot how would you do that
Hope this would help

How to read data using JSONP, Ajax and jquery?

I am trying to read data from this API, but it is not working, I have an input box where I enter the isbn number and then get the data, using jsonp. Could you possibly help me in identifying where my error("Cannot read property 'title' of undefined") is?
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(isbn){
var infoUrl = isbn.info_url;
var thumbnailUrl = isbn.thumbnail_url;
var title = isbn.details.title;
var publishers = isbn.details.publishers;
var isbn13 = isbn.details.isbn_13;
console.log(isbn.info_url);
}
});
}
Open Library's API expects bibkeys to be prefixed with their type and a colon, rather than just the number alone:
function add(){
var isbn = 'ISBN:' + $("#isbn").val();
// ...
The colon also means the value should be URL-encoded, which jQuery can do for you:
$.ajax({
url: "https://openlibrary.org/api/books?jscmd=details&callback=?",
data: { bidkeys: isbn },
dataType: "jsonp",
Then, the data it returns reuses the bibkeys you provided as properties:
{ "ISBN:0123456789": { "info_url": ..., "details": { ... }, ... } }
To access the book's information, you'll have to first access this property:
success: function(data){
var bookInfo = data[isbn];
console.log(bookInfo.details.title);
// etc.
}
Example: https://jsfiddle.net/3p6s7051/
You can also retrieve the bibkey from the object itself using Object.keys():
success: function (data) {
var bibkey = Object.keys(data)[0];
var bookInfo = data[bibkey];
console.log(bookInfo.details.title);
// ...
}
Note: You can use this to validate, since the request can be technically successful and not include any book information (i.e. no matches found):
success: function (data) {
var bibkeys = Object.keys(data);
if (bibkeys.length === 0)
return showError('No books were found with the ISBN provided.');
// ...
Example: https://jsfiddle.net/q0aqys87/
I asked a professor, and this is how she told me to solve it:
function add(){
var isbn = parseInt($("#isbn").val());
var list = $("#list");
console.log(parseInt(isbn));
$.ajax({
url: "https://openlibrary.org/api/books?bibkeys=" + isbn + "&jscmd=details&callback=mycallback",
dataType: "jsonp",
success: function(data){
var thumb=data["ISBN:"+isbn+""].thumbnail_url;
....
}
});
}

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"
});

Add Property dynamically to the JSON array

I would like to two add property Id and ButtonId to the exisiting json result. I have pasted the below js code for reference and I would like to pass the jsonresult to MVC controller. As of now it returns null. please help to proceed. Thanks.
my final result should look like this
json{"Groups":{"Id":"2","ButtonId":"1142","1186","1189"},
{"Id":"3","ButtonId":"1171","1173","1174","1175","1176","1187"},
{"Id":"4","ButtonId":"1177","1178","1179"}} etc..
var btnlist = {Groups: {Id:"", ButtonId: ""}};
$.each($(".buttonData"), function (index, value) {
var values = value.id.split(':');
grpid = values[0].split('-')[1];
btnid = values[1].split('-')[1];
console.log('grpid=' + grpid + ' btnid=' + btnid);
if (typeof (btnlist['Groups'][grpid]) == 'undefined') {
btnlist['Groups'][grpid] = [];
}
btnlist['Groups'][grpid].push(btnid);
});
$.ajax({
type: "POST",
url: "#Url.Action("Home", "Menu")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(btnlist) ,
success: function (result) {
console.log('json' + JSON.stringify(btnlist));
console.debug(result);
},
error: function (request, error) {
console.debug(error);
}
});
This is the json result before pushing into the multidimensional array
The json result, where the properties Id and ButtonId is inserted behind.
null result passed to the controller
With assistance of my colleague, the desired output is as below. This is for other programmers who face similar issue with JSON array. Thanks.
var btnlist = [];
btngrps = $('.btn-sort-container');
$.each(btngrps, function(k, v) {
btnarr = {};
gid = $(this).attr('id');
grpid = gid.split('-')[1];
btnarr.Id = gid.split('-')[1];
btnobjs = $(v).find('.buttonData');
if (btnobjs.length) {
btnarr['btnId'] = [];
$.each(btnobjs, function(bk, bv) {
btnid = $(bv).attr('id').split('-')[2];
btnarr['btnId'].push($(bv).attr('id').split('-')[2]);
});
console.debug(btnarr);
btnlist.push(btnarr);
}
});
console.debug(btnlist);
Output on console
: http://i.stack.imgur.com/oJ3Dy.png

Categories

Resources