I have just this array :
var sArray = {856:"users", 857:"avatars", 858:"emails"};
and I want to use forEach in a way to get key and value from that:
key = 856
value = user
My $.each code doesn't return the result I'm expecting, and I get instead:
856:user
I must be separate that with : to get key and value from this array.
My code is:
$.each(template_array, function(key, value) {
console.log("key: " + "value: " + value);
});
How to access key and value without separate?
Just take Object.keys for the keys and Array.prototype.forEach for the values in plain Javascript.
var sArray = { 856: 'users', 857: 'avatars', 858: 'emails'};
Object.keys(sArray).forEach(function (key) {
document.write('key: ' + key + ', value: ' + sArray[key] + '<br>');
});
Just concatenate them using +
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
$.each(template_array, function(key, value) {
console.log('key:' + key + ', value:' + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
UPDATE :
I think you have an array then use the following code
var template_array = ['856: users',
'857: avatars',
'858: emails'
];
template_array.forEach(function(v) {
v = v.split(':');
console.log('key:' + v[0] + ', value:' + v[1]);
});
try this one
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
var date = [];
$.each(template_array,function (key , val){
date.push({key:key, value:val})
});
console.log(date)
var template_array = {
856: 'users',
857: 'avatars',
858: 'emails'
};
for (key in template_array) {
console.log('key:' + key + ', value:' + template_array[key]);
});
Related
i have been tasked by my senior to print values of line items using higher order functions (.filter/.map/.reject/.reduce). I m confused how to write the higher order function instead of a for loop(for printing the line values in Invoice Printout). I need to print the line only when the qty is more than 3. I m an intern and i dont know how it will work, kindly help.
Link to The code snippet: https://drive.google.com/file/d/1uVQQb0dsg_bo53fT3vk9f0G8WwZomgQg/view?usp=sharing
I always used if condition for printing the row only when the quantity field has value more than 3. I even know how to .filter but i dont know how to call it and where to call it. Please help
I don't believe Array.from works in server side code. If it does then use that. What I have been using are the following functions. They don't conform to the higher order functions specified but they work with Netsuite syntax and go a long way towards simplifying sublist handling and encapsulating code:
//SS2.x
//I have this as a snippet that can be included in server side scripts
function iter(rec, listName, cb){
var lim = rec.getLineCount({sublistId:listName});
var i = 0;
var getV = function (fld){
return rec.getSublistValue({sublistId:listName, fieldId:fld, line:i});
};
for(; i< lim; i++){
cb(i, getV);
}
}
// to use it:
iter(ctx.newRecord, 'item', function(idx, getV){
if(parseInt(getV('quantity')) >3){
...
}
});
or for SS1 scripts I have the following which allows code to be shared between UserEvent and Scheduled scripts or Suitelets
function forRecordLines(rec, machName, op, doReverse) {
var i, pred, incr;
var getVal = rec ? function(fld) {
return rec.getLineItemValue(machName, fld, i);
} : function(fld) {
return nlapiGetLineItemValue(machName, fld, i);
};
var getText = rec ? function(fld) {
return rec.getLineItemText(machName, fld, i);
} : function(fld) {
return nlapiGetLineItemText(machName, fld, i);
};
var setVal = rec ? function(fld, val) {
rec.setLineItemValue(machName, fld, i, val);
} : function(fld, val) {
nlapiSetLineItemValue(machName, fld, i, val);
};
var machCount = rec ? rec.getLineItemCount(machName) : nlapiGetLineItemCount(machName);
if(!doReverse){
i = 1;
pred = function(){ return i<= machCount;};
incr = function(){ i++;};
}else{
i = machCount;
pred = function(){ return i>0;};
incr = function(){ i--;};
}
while(pred()){
var ret = op(i, getVal, getText, setVal);
incr();
if (typeof ret != 'undefined' && !ret) break;
}
}
// User Event Script:
forRecordLines(null, 'item', function(idx, getV, getT, setV){
if(parseInt(getV('quantity')) >3){
...
}
});
// in a Scheduled Script:
forRecordLines(nlapiLoadRecord('salesorder', id), 'item', function(idx, getV, getT, setV){
if(parseInt(getV('quantity')) >3){
...
}
});
Usually its a straight forward task, but since you are getting length and based on that you are iterating, you can use Array.from. Its signature is:
Array.from(ArrayLikeObject, mapFunction);
var tableData = Array.from({ length: countItem}, function(index) {
vendorBillRec.selectLineItem('item', index);
var item = vendorBillRec.getCurrentLineItemText('item', 'item');
var description = nlapiEscapeXML(vendorBillRec.getCurrentLineItemValue('item', 'description'));
var quantity = parseFloat(nullNumber(vendorBillRec.getCurrentLineItemValue('item', 'quantity')));
return { item, description, quantity}
});
var htmlData = tableData.filter(...).map(getRowMarkup).join('');
function getRowMarkup(data) {
const { itemName, descript, quantity } = data;
return '<tr>' +
'<td colspan="6">' +
'<p>' + itemName + ' ' + descript + '</p>'+
'</td>' +
'<td colspan="2" align="right">' + quantity + '</td>' +
'</tr>';
}
Or if you like to use more functional approach:
Create a function that reads and give you all data in Array format. You can use this data for any task.
Create a function that will accept an object of specified properties and returns a markup.
Pass the data to this markup after any filter condition.
Idea is to isolate both the task:
- Getting data that needs to be processed
- Presentation logic and style related code
var htmlString = Array.from({ length: countItem}, function(index) {
vendorBillRec.selectLineItem('item', index);
var item = vendorBillRec.getCurrentLineItemText('item', 'item');
var description = nlapiEscapeXML(vendorBillRec.getCurrentLineItemValue('item', 'description'));
var qty = parseFloat(nullNumber(vendorBillRec.getCurrentLineItemValue('item', 'quantity')));
return getRowMarkup(item, description, qty)
}).join('');
function getRowMarkup(itemName, descript, quantity) {
return '<tr>' +
'<td colspan="6">' +
'<p>' + itemName + ' ' + descript + '</p>'+
'</td>' +
'<td colspan="2" align="right">' + quantity + '</td>' +
'</tr>';
}
This is my code:
I want to get the first value of the arrays in every property, but it doesnt work. Thanks for help.
var arena = {
o1: ['gate',1,1],
o2: ['block',1,1]
};
$(document).ready(function(){
var canvas = document.getElementById('canvas.arena');
var xpercent = canvas.width/100;
var ypercent = canvas.height/100;
for (var key in arena) {
if (arena.hasOwnProperty(key)) {
console.log(key + " -> " + arena[key[0]]);
}
}
});
Almost:
for (var key in arena) {
console.log(key + " -> " + arena[key][0]);
}
key will always be a property, no need to check.
you are very close:
var arena = {
o1: ['gate',1,1],
o2: ['block',1,1]
};
$(document).ready(function(){
for (var key in arena) {
console.log(key + " -> " + arena[key][0]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
prepared this fiddle:
https://jsfiddle.net/njvf58ow/1/
I'm trying to build a new project.
It's going to be a tradebot for a website, now to store my received items into my database i whould like some info send with each item (being the name , asseid , tradeid,...).
The following code works.
offers.on('receivedOfferChanged', function (offer, oldState) {
logger.info(offer.partner.getSteam3RenderedID() + " Offer #" + offer.id + " changed: " + TradeOfferManager.getStateName(oldState) + " -> " + TradeOfferManager.getStateName(offer.state));
// Alert us when we accept an offer
if (offer.state == TradeOfferManager.ETradeOfferState.Accepted) {
offer.getReceivedItems(function (err, items) {
if (err) {
logger.error("Couldn't get received items: " + err);
} else {
var names = items.map(function(item) {
return item.name;
});
var assetids = items.map(function(item) {
return item.assetid;
});
// Log a comma-separated list of items received
logger.info("Received: " + names + " " + assetids.join(', '));
}
});
}
});`
But the thing is, is there any way to shorten the following code :
var names = items.map(function(item) {
return item.name;
});
var assetids = items.map(function(item) {
return item.assetid;
});
So it gets the item name , assetid, ... out of the array and stores them in sperate variables ?
You can use push() method to add values into both arrays in a single loop. Try:
var names = [],
assetids = [];
items.forEach(function(item) {
assetids.push(item.assetid);
names.push(item.name);
});
i have a json object that has item type and id, i need to create new object
var data = {
"items":[
{"type":"generator","id":"item_1","x":200,"y":200},
{"type":"battery","id":"item_2","x":50,"y":300},
{"type":"generator","id":"item_3","x":200,"y":280},
{"type":"battery","id":"item_4","x":100,"y":400}
]
};
and i need to run for each item in items
jQuery.each(data.items, function(index,value) {
eval("var " + value.id + " = new " + value.type + "(" + (index + 1) + ");");
eval(value.id + ".id = '" + value.id + "';");
eval(value.id + ".draw(" + value.x + "," + value.y + ");")
});
this is not a good practice, but what else can i do?
i need then to have the control on the items
something like
item_1.moveto(300,700);
but i always get item_1 is undefind
You can create a factory method which allows to generate concrete types out of an abstract data structure:
var createItem = (function () {
var types = {};
function createItem(index, data) {
data = data || {};
var ctor = types[data.type], item;
if (!ctor) throw new Error("'" + data.type + "' is not a registered item type.");
item = new ctor(index);
item.id = data.id;
return item;
}
createItem.registerType = function (type, ctor) {
types[type] = ctor;
};
return createItem;
})();
Then register item types to the factory:
function Generator(index) {/*...*/}
createItem.registerType('generator', Generator);
And finally create an object map to lookup your items by id (you could use a specialized object like ItemsMap instead of a plain object), loop through your items and add them to the map.
var itemsMap = {};
data.items.forEach(function (itemData, i) {
var item = itemsMap[itemData.id] = createItem(i + 1, itemData);
//you can also draw them at this point
item.draw(itemData.x, itemData.y);
});
You can now lookup objects by id like:
var item1 = itemsMap['item_1'];
var objects = {};
objects[value.id] = new window[value.type](index + 1);
I have this set
var data = [
{"outlet_name":"Easy Lane Supermart","20130102_20130108":"0"},
{"outlet_name":"Eunilaine Foodmart Kalayaan","20130102_20130108":"0"},
{"outlet_name":"PUREGOLD PRICE CLUB, INC - VISAYAS","20130102_20130108":"0"}
];
$.each(data, function (i, item) {
$.each(item, function (k,v) {
$('#result').append(k,v);
});
});
How can I make it only view all the values of outlet_name without using the item.outlet_name?
$.each(data, function (i, item) {
console.log(item.outlet_name);
});
Or without jQuery:
for (var i=0;i<data.length;i+=1) {
console.log(data[i].outlet_name);
}
Ok, if you want to iterate over each object you can write:
$.each(data, function (i, item) {
console.log("Values in object " + i + ":");
$.each(item, function(key, value) {
console.log(key + " = " + value);
});
});
This will provide exact answer...
var data = [
{"outlet_name":"Easy Lane Supermart","20130102_20130108":"0"},
{"outlet_name":"Eunilaine Foodmart Kalayaan","20130102_20130108":"0"},
{"outlet_name":"PUREGOLD PRICE CLUB, INC - VISAYAS","20130102_20130108":"0"}
];
for(i=0;i<data.length;i++){
for(var x in data[i]){
console.log(x + " => " + data[i][x]);
}
}
If anyone is needing to do this from a JSON string for example
var myJson = [{"Code":"slide_1.png","Description":"slide_1"},{"Code":"slide_2.png","Description":"slide_2"},{"Code":"slide_3.png","Description":"slide_3"}]
You can use
var newJsonArray = JSON.Parse(myJson) and you will get
Array[3]
0
:
Object
1
:
Object
2
:
Object
At which point you can access it by simply saying newJsonArray[i].Code or whatever property inside the array you want to use. Hope this helps!