Pass variable to anon function / callback - javascript

I am trying to pass product into the find() function that contains a .toArray() anonymous function containing both error and array. Unfortunately this entire find() function runs within an iteration and only the first value goes in. How do I pass product to the callbacks?
var find = function(product,callbacks){
foos.find({
"foo": product.bars,
}).toArray(function (error, array) {
if(error){
callbacks.error(product,error);
} else if (array.length == 0) {
callbacks.none(product);
} else {
callbacks.exists(product);
}
});
}

Before this function i was processing products with forEach() then had this run in a callback within that. This was big trouble. Processed products with a regular for and now it works.
Old code
var products = function(data,callback){
products.forEach(function(product){
insert.product_id = product.id;
var variants = product.variants;
variants.forEach(function(variant){
insert.sku = variant.sku;
insert.variant_id = variant.id;
return callback(insert);
});
});
}
New code
var products = function(data){
var insert = [];
var products = data.products;
for(var pKey in products){
var product = products[pKey];
var variants = product.variants;
var set = {}
set.product_id = product.id;
for(var vKey in variants){
var variant = variants[vKey];
set.sku = variant.sku;
set.variant_id = variant.id;
insert.push(set);
}
}
return insert;
}

Related

Concat in a for loop google app scripts javascript

I'm trying to filter in an array by data in another array using concat in a for loop. The elements of the following code are logging correctly, but the final array is logging an empty array.
function Shipments (){
var app = SpreadsheetApp;
var movementSS = app.getActiveSpreadsheet();
var infoSheet = movementSS.getSheetByName("Update Info");
var orderInfoSheet = movementSS.getSheetByName("Order Info");
var targetSheet = movementSS.getSheetByName("Shipments");
var ShipLogSS = app.openByUrl(URL).getSheetByName("Shipping Details");
var ShipArr = ShipLogSS.getRange(3,1,ShipLogSS.getLastRow(),ShipLogSS.getLastColumn()).getValues().
filter(function(item){if(item[1]!=""){return true}}).
map(function(r){return [r[0],r[1],r[2],r[4],r[10],r[11],r[16],r[18],r[23]]});
var supplierData = orderInfoSheet.getRange(3,6,orderInfoSheet.getLastRow(),1).getValues().
filter(function(item){if(item[0]!=""){return true}});
var supplierList = [];
for (var i in supplierData) {
var row = supplierData[i];
var duplicate = false;
for (var j in supplierList) {
if (row.join() == supplierList[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
supplierList.push(row);
}
}
var supplierFilter = [];
for(var i = 0; i < supplierList.length; i++){
var shipments = ShipArr.filter(function(item){if(item[4]===supplierList[i][0]){return true}});
supplierFilter.concat(shipments);
}
Logger.log(supplierFilter);
}
Any help would be greatly appreciated!
You need to assign the result of concat onto the supplierFilter in order to see the changes in later iterations and in the outer scope.
You can also return the comparison done inside the .filter callback immediately, instead of an if statement - it looks a bit cleaner.
var supplierFilter = [];
for (var i = 0; i < supplierList.length; i++) {
var shipments = ShipArr.filter(function (item) { return item[4] === supplierList[i][0]; });
supplierFilter = supplierFilter.concat(shipments);
}
Logger.log(supplierFilter);

C# class only returning first item of a JavaScript array - cant update just one record of db

I have a grid in html with some data of example Directors. Then I change the data, and want to update db.
Using a JS function, I get all the details from the grid, and save it in an array.
function getDirectorGridDetails() {
var tableRows = document.getElementById("tc_directorsGrid_table").rows
for (var i = 0; i < tableRows.length; i++) {
var directorRow = tableRows[i]
if (directorRow) {
var directorRowSeq = directorRow.getAttribute("data-id");
var directorDetailDesc = directorRow.getElementsByTagName("td")[0].innerHTML;
var directorDetailGender = directorRow.getElementsByTagName("td")[1].innerHTML;
var directorDetailDateApp = directorRow.getElementsByTagName("td")[2].innerHTML;
var directorDetailDateRes = directorRow.getElementsByTagName("td")[3].innerHTML;
if (!x) {
var x = [];
var Seq = [];
var Description = [];
var Gender = [];
var DateAppointed = [];
var DateResigned = [];
}
Seq.push(directorRowSeq);
Description.push(directorDetailDesc);
Gender.push(directorDetailGender);
DateAppointed.push(directorDetailDateApp);
DateResigned.push(directorDetailDateRes);
}
else {
break;
}
}
var directorsclass = {
"directorsclass": {
"Seq": Seq,
"Description": Description,
"Gender": Gender,
"DateAppointed": DateAppointed,
"DateResigned": DateResigned
}
}
return directorsclass
};
then, when I enter my C# side, to get the details and update db, the class is only returning the first items of the array.
Is there a way of getting each object from array, pass that in to class?
c# code snippit
[HttpPost]
[Route("client/updateDirector")]
public ActionResult updateDirector([System.Web.Http.FromBody] DirectorsClass directorsclass)
{}
when it get to directorsclass, it only shows first element

Calling an array item into another array

I faced the following functions (or method I don't what is right name of the ):
function getRowArray($scope, object, i){
i = i + 1;
var item = {};
var data = [];
var id = -1;
if ($scope.selectedType !== undefined) {
id = $scope.selectedType.id;
}
var rating = getRating($scope, object, id);
item['name'] = $scope.objectInfo[object]['name'];
item['objectId'] = rating.objectId;
item['hideRating'] = parseInt($scope.objectInfo[object].hideControls) & 1;
item['addInfo'] = rating.addInfo;
item['rating'] = rating.value;
item['ratingId'] = rating.id;
for (var i in $scope.objectInfo[object].childs) {
if ($scope.objectInfo[object].childs[i] == object){
continue;
}
data.push(getRowArray($scope, $scope.objectInfo[object].childs[i], i));
}
item['data'] = data;
return item;
}
and
function getTypeRow($scope, oobject, otype){
var item = {};
var data = [];
var rating = getRating($scope, oobject.id, otype.id);
item['name'] = otype.name;
item['objectId'] = rating.objectId;
item['typeId'] = rating.typeId;
item['ratingId'] = rating.id;
item['addInfo'] = rating.addInfo;
item['rating'] = rating.value;
// item['hideRating'] = parseInt($scope.objectInfo[object].hideControls);
return item;
}
I want to use the hideRating item from the first one in the second, I tried and added the commented line but I got an error it says the object is undifined, is it wrong like that or am I missing something ? thanks in advance
object is undefined because it wasn't initialized; it's not specified in the parameter list for the function getTypeRow. The oobject in the parameter list should be corrected to object:
// Correct 'oobject' to 'object'
function getTypeRow($scope, object, otype){
var item = {};
var data = [];
// Correct 'oobject' to 'object'
var rating = getRating($scope, oobject.id, otype.id);
...
}

Why ScriptDb query result object is different

function myFunction() {
var item = {};
item = {id:'myId', rules: {1:'rule1', 2:'rule2'}};
Logger.log(item); // {id=myId, rules={2=rule2, 1=rule1}}
Logger.log(item.rules[1]); // rule1
var db = ScriptDb.getMyDb();
db.save(item);
var result = db.query({id:'myId'});
item = result.next();
Logger.log(item); // {id=myId, rules={2=rule2, 1=rule1}}
Logger.log(item.rules[1]); // undefined, why?
}
Expecting the last log to return the value "rule1" like in the original object.
Why is it now undefined?
A strange case, it may be a bug.
With the following code can get what you need:
...
item = JSON.parse(item.toJson());
Logger.log(item); // {id=myId, rules={2=rule2, 1=rule1}}
Logger.log(item.rules[1]); // rule1
...
An alternative route for storing and filtering results with a numerical value instead of with a numerical key.
function myFunction() {
var db = ScriptDb.getMyDb();
var item1 = {id:'myId', rule:{num:1, details:'rule1'}};
var item2 = {id:'myId', rule:{num:2, details:'rule2'}};
var saveResults = db.saveBatch([item1, item2], false);
var results = db.query({id:'myId'});
while (results.hasNext()) {
var item = results.next();
if (item.rule.num == 1)
Logger.log(item.rule.details); // rule1
}
}

Javascript | Objects, Arrays and functions

may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);

Categories