jQuery JSON I continue to get [object Object] as a value - javascript

I was updating the script for my site to allow for API changes from v1 to v2 the changes being
V1
"ISteamClient": 0,
etc..
V2
"ISteamClient": {
"online": 1
},
etc..
But now when I write what val is for each of the parts I get [object Object] in return, so I found a guide in which I call val['online'] but I still get [object Object]. I haven't done much work with JSON, just simple first layer JSON (like V1)
function loadup() {
$.getJSON("https://steamgaug.es/api/v2", function(data) {
var items = [];
var ISteamClient = 2,
ISteamCommunity = 2,
ISteamGameCoorindator_440 = 2,
ISteamUser = 2,
IEconItems_440 = 2;
$.each(data, function(key, val) {
if (key === "ISteamClient") {
ISteamClient = val['online'];
console.log(key + " = " + val);
}
else if (key === "SteamCommunity") {
ISteamCommunity = val['online'];
console.log(key + " = " + val);
}
else if (key === "ISteamGameCoorindator_440") {
ISteamGameCoorindator_440 = val['online'];
console.log(key + " = " + val);
}
else if (key === "ISteamUser") {
ISteamUser = val['online'];
console.log(key + " = " + val);
}
else if (key === "IEconItems_440") {
IEconItems_440 = val['online'];
console.log(key + " = " + val);
}
});
//Sort and group data
});
}
What am I doing wrong?

You're logging val, which is an object.
I think you want to log val.online

Related

Unable to send dynamic invoice value to struts2 server

I am working on angularjs 1.6.5
I am using following code to send data of invoice page.
$scope.products = [{qty: 0, description: ' ', sellingPrice: 0.0, unitPrice: 0.0, total: 0.0}];
$scope.fproducts = [];
$scope.generateInvoice = function () {
console.log("generateInvoice");
console.log($scope.fproducts);
console.log("sub total " + $scope.subTotal + " ft " + $scope.finalTotal + " pamt " + $scope.paidAmount + " baldue " + $scope.balancedue);
$scope.bd1 = {
'subTotal': $scope.subTotal,
'total': $scope.finalTotal,
'TotalPaid': $scope.paidAmount,
'invDateStr': $filter('date')($scope.invoiceDate, "MM/dd/yyyy"),
};
if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}].${key}`] = value;
});
});
}
//commenting above for each and removing comment from below code is
// working properly but I want to send dynamic data with above code
/* $scope.bd1[`billProductList[0].id`] = 1;
$scope.bd1[`billProductList[0].description`] = 1;
$scope.bd1[`billProductList[0].discountPercent`] = 150;
$scope.bd1[`billProductList[0].qty`] = 10;
$scope.bd1[`billProductList[0].sellingPrice`] = 100;
$scope.bd1[`billProductList[0].unitPrice`] = 100;
$scope.bd1[`billProductList[0].total`] = 150;*/
$scope.bd1[`BillPaidDetailses[0].paymentMode`] = $scope.paymentMode;
$scope.bd1[`BillPaidDetailses[0].amount`] = $scope.paidAmount;
console.log($scope.bd1);
$http({
method: 'POST',
url: 'added-invoice',
data: $httpParamSerializerJQLike($scope.bd1),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(data, status, headers, config) {
if (data.data.st === 1) {
$scope.success = true;
window.location = 'bhome#!/show-tax';
} else if (data.data.st === 0) {
$scope.success = false;
$scope.failure = true;
} else if (data.data.st === -1) {
$scope.success = false;
$scope.failure = true;
}
}, function errorCallback(data, status, header, config) {
$scope.success = false;
$scope.failure = true;
});
}
Above code is not passing value to server side object.
its console.log value is
on modifying above data
/*if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}].${key}`] = value;
});
});
}*/
$scope.bd1[`billProductList[0].id`] = 1;
$scope.bd1[`billProductList[0].description`] = 1;
$scope.bd1[`billProductList[0].discountPercent`] = 150;
$scope.bd1[`billProductList[0].qty`] = 10;
$scope.bd1[`billProductList[0].sellingPrice`] = 100;
$scope.bd1[`billProductList[0].unitPrice`] = 100;
$scope.bd1[`billProductList[0].total`] = 150;
as this is passing value to server object
its console.log is
I want to run my code using dynamic value specified in if condition.
What is the problem I am unable to get it.
EDIT I am using server side struts2
my code is
public class BillNewAction extends ActionSupport implements ModelDriven<BillDetails> {
BillDetails bd = new BillDetails();
private List<BillDetails> billList = new ArrayList<BillDetails>();
public String insert() {
System.out.println("total " + bd.getTotal()
+ " subTotal " + bd.getSubTotal() + " paid "
+ bd.getTotalPaid()
+ " invoiceDate " + bd.getInvDateStr()
);
SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy");
try {
bd.setInvoiceDate((new java.sql.Date(formatter1.parse(bd.getInvDateStr()).getTime())));
} catch (ParseException ex) {
Logger.getLogger(BillNewAction.class.getName()).log(Level.SEVERE, null, ex);
}
for (BillPaidDetails b : bd.getBillPaidDetailses()) {
System.out.println("type " + b.getPaymentMode() + " amount "
+ b.getAmount()
);
}
System.out.println("product size " + bd.getBillPrList().size());
for (BillProduct b : bd.getBillPrList()) {
System.out.println("id " + b.getId() + " desc "
+ b.getDescription() + " qty " + b.getQty()
+ " sp " + b.getSellingPrice() + " up "
+ b.getUnitPrice() + " " + b.getTotal()
);
}
}
}
public class BillDetails implements java.io.Serializable {
private Long billNo;
private Client client;
private BigDecimal subTotal;
private BigDecimal TotalAmount;//total price
private BigDecimal TotalPaid;//Amount paid for getting items
private BigDecimal vat;
private BigDecimal total;
private String invoiceNo;
private Date invoiceDate;
private String invDateStr;
private List<BillPaidDetails> BillPaidDetailses = new ArrayList<BillPaidDetails>();
private List<BillProduct> billPrList = new ArrayList<BillProduct>();
//getter and setter
}
I have to send data in $scope.bd1[billProductList[0].id] = 1; format to server
Assigning indivisual value passing the data to server but I have dynamic no of values so I am trying
if ($scope.fproducts.length > 0) {
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value]) => {
console.log(index + " " + key + " " + value);
$scope.bd1[billProductList[${index}].${key}] = value;
});
});
}
that is not working
Consider using the Struts JSON Plugin
The JSON plugin provides a json result type that serializes actions into JSON.
The content-type must be application/json
Action must have a public “setter” method for fields that must be populated.
Supported types for population are: Primitives (int,long…String), Date, List, Map, Primitive Arrays, other class, and Array of Other class.
Any object in JSON, that is to be populated inside a list, or a map, will be of type Map (mapping from properties to values), any whole number will be of type Long, any decimal number will be of type Double, and any array of type List.
Your actions can accept incoming JSON if they are in package which uses json interceptor or by adding reference to it.
This simplifies the AngularJS HTTP POST request:
$scope.bd1 = {
'subTotal': $scope.subTotal,
'total': $scope.finalTotal,
'TotalPaid': $scope.paidAmount,
'invDateStr': $scope.invoiceDate.toISOString(),
'billProductList': $scope.fproducts,
};
$http({
method: 'POST',
url: 'added-invoice',
data: $scope.bd1,
headers: {'Content-Type': 'application/json'}
}).then(function successCallback(response) {
var data = response.data;
if (data.st === 1) {
$scope.success = true;
window.location = 'bhome#!/show-tax';
} else if (data.st === 0) {
$scope.success = false;
$scope.failure = true;
} else if (data.data.st === -1) {
$scope.success = false;
$scope.failure = true;
}
}, function errorCallback(response) {
$scope.success = false;
$scope.failure = true;
});
$scope.bd1[billProductList[${index}].${key}] = value; you are overriding value on this line of code
$scope.bd1[billProductList[${index}${index2}].${key}] you can change shape of object as per you need
$scope.fproducts.forEach((total, index) => {
Object.entries(total).forEach(([key, value],index2) => {
console.log(index + " " + key + " " + value);
$scope.bd1[`billProductList[${index}${index2}].${key}`] = value;
});
})
That may be because console.log(index + " " + key + " " + value) is returning correct value as you are getting inside loop.
try to access the below piece of code, after assigning to $scope.bd1:
Object.entries(total).forEach(([key, value]) => {
$scope.bd1[`billProductList[${index}].${key}`] = value;
console.log($scope.bd1[`billProductList[${index}].${key}`]);
});
And I guess $scope.bd1 is not getting updated hence it is not passing value to server side object.

how to run different sessions of same domain in same browser?

I want to login with multiple logins for the domain in same browser.
example there is a messaging service call slack if i login in first tab and if i open second tab in same browser it should no share session with second tab it should be altogether a new one.
I've tried below block of code but it is not working how do i acheive this
var clearLocal = window.localStorage.clear.bind(window.localStorage);
var getLocal = window.localStorage.getItem.bind(window.localStorage);
var keyLocal = window.localStorage.key.bind(window.localStorage);
var removeLocal = window.localStorage.removeItem.bind(window.localStorage);
var setLocal = window.localStorage.setItem.bind(window.localStorage);
window.localStorage.getItem = function(key) {
alert("inside account key " + key);
var newKey = accountId + "::" + key;
alert("inside account new key " + newKey);
return getLocal(newKey);
}
window.localStorage.key = function(index) {
console.log("KEY " + index);
return keyLocal(index);
}
window.localStorage.removeItem = function(key) {
var newKey = accountId + "::" + key;
console.log("REMOVE " + newKey);
return removeLocal(newKey);
}
window.localStorage.setItem = function(key, value) {
var newKey = accountId + "::" + key;
alert("inside account new key " + newKey);
return setLocal(newKey, value);
}
Any suggestions more appreciated..

How do I convert the object passed in to an array of strings

function objectToArray (object) {
var array = [];
var str = "";
for (var key in object) {
array.push(key);
array.push(object[key]);
if (object.hasOwnProperty(key)) {
str += key + " is " + object[key] + "";
}
}
console.log(array);
}
objectToArray({name: "Marcia", age: 101});
The output is [ 'name', 'Marcia', 'age', 101 ] and I need it to be ["name is Marcia", "age is 101"].
Instead of this:
array.push(key);
array.push(object[key]);
if (object.hasOwnProperty(key)) {
str += key + " is " + object[key] + "";
}
You want this:
if (object.hasOwnProperty(key)) {
array.push( key + " is " + object[key] + "" );
}
#VoteyDisciple has correctly pointed out where you went wrong with your approach. An alternate (shorter) way to implement your function is:
function objectToArray (object) {
return Object.keys(object).map(function (key) {
return key + " is " + object[key];
});
}
var arr = objectToArray({name: "Marcia", age: 101});
console.log(arr);

Getting Uncaught TypeError: Cannot read property 'get' of undefined in spite of the conditionals

I'm trying to retrieve images on Facebook Parse SDK, and I can't because of this error. And I don't know what i'm doing wrong because I use a conditional in order to no not to create a new variable if this is empty or undefined. This is the code (the console log points the error in the line where i'm creating the var ImageFl):
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
if (!object.get('ImageFile') || object.get('ImageFile') !== '' || typeof object.get('ImageFile') !== 'undefined') {
var imageFl = object.get('ImageFile');
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
var object = results[i];
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
The object wasn't being set before the if statement. update, added code from comments
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i]; // <-- THIS NEEDS TO BE BEFORE IF STATEMENT
var imageFl = object.get('ImageFile');
alert(imageFl);
if (imageFl !== '' && typeof imageFl !== 'undefined') {
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});

Constraint-less Parse query returns blank objects

I've usually been making queries to a class for a single, directed object using the objectId and it's all been working smoothly. However I am now trying to get all of the objects in a given class.
var values;
var Class = Parse.Object.extend(className);
var query = new Parse.Query(Class);
console.log(objectID);
if (typeof objectID !== "undefined") { //if the user specified objectID
query.get(objectID, {
success: function(retrieveObject) {
for (var i = 0; i < keys.length; i++) {
values[i] = query.get(keys[i]);
}
},
error: function(error) {
console.log("Failed to retrieve " + className + ': ' + error.message);
}
});
} else { //if not return all
query.limit(1000);
query.exists("objectId");
query.find({
success: function(results) {
console.log("the results are " + results);
for (var i = 0; i < results.length; i++) {
for (var j = 0; j < keys.length;j ++)
console.log("key " + j + " is " + keys[j]);
console.log("the result for " + j + " is " + results[i]);
var object = results[i];
values[i][j] = object.get(keys[j]);
console.log("the value for the key in result is " + values[i][j]);
}
},
error: function(error) {
console.log("Failed to retrieve " + className + ': ' + error.message);
}
});
}
For the life of me I cannot figure out why this does not work. "results" comes out as an array of the correct number of values, but each is "[object Object]"
Any ideas?

Categories