printing the json array from certain indexes - javascript

guys i know it is dummy question but i spent several hours and still cant reach .. i want to print a json array from variable startIndex and endIndex .. all what i did is printing it all .. here is my code
GridLibrary.prototype.display = function() {
$.ajax({
url : this.getFileName(),
dataType : "json",
error : function(that, e) {
console.log(e);
},
success : function(data) {
size = data.length;
var html = [];
html.push("<table >\n<tbody>");
html.push("<tr>");
for ( var propertyNames in data[0]) {
html.push("<th>" + propertyNames + "</th>");
}
html.push("</tr>");
// loop through the array of objects
data.forEach(function(item) {
html.push("<tr>");
for ( var key in item) {
html.push("<td>" + item[key] + "</td>");
}
html.push("</tr>");
});
html.push("<table>\n</tbody>");
$('body').append(html.join(""));
}
});
};

try this, loop through only the data you need
for( var i = startIndex; var item = data[i]; i<endIndex && typeof item != 'undefined' ; i++){
html.push("<tr>");
for ( var key in item) {
html.push("<td>" + item[key] + "</td>");
}
html.push("</tr>");
}

Just before your data.forEach(...) you could use splice() to cut your data array.
Like this:
data = data.splice(startIndex, endIndex);

Related

How to use higher order functions instead of FOR Loop for Line items in Suitelet printouts (Netsuite)?

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>';
}

JQuery : How to add list of objects in Ajax

It's one of my first time I using JQuery/AJAX and I would like to get your help in order to give a list of objects in my dropdown field.
I have this function :
function get_sub_method_options(keep_cur) {
var sel_option = $('select#id_method-group').find("option:selected");
var sel_val = sel_option.val();
console.log(sel_val);
if (sel_val === '') {
console.log('none sorting group');
$("select#id_method-sub_method").empty();
$("select#id_method-sub_method").append('<option value=""> test </option>'); //here add list of all submethods
return;
}
data = {
'test_method': $('select#id_method-test_method').find("option:selected").val(),
'group': sel_val
};
$.ajax({
method: "GET",
url: '{% url 'ajax_method_submethod' %}',
data: data
}).done(function (result) {
reset_select('id_method-sub_method');
for (var i = 0; i < result['results'].length; i++) {
if (keep_cur > 0 & keep_cur == result['results'][i].id)
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '" selected>' + result['results'][i].text + '</option>');
else
$("select#id_method-sub_method").append('<option value="' + result['results'][i].id + '">' + result['results'][i].text + '</option>');
}
;
});
}
And I have a Python/Django function :
def ajax_method_submethod(request):
test_method_id = request.GET.get("test_method", "")
group_id = request.GET.get("group", "")
sub_methods_all = SubMethod.objects.all()
sub_methods = Method.objects.filter(test_method_id=test_method_id).filter(
group_id=group_id
)
results2 = []
for item in sub_methods_all:
results2.append({'id': item.id, 'text': item.name})
print(results2)
results = []
for item in sub_methods:
results.append({'id': item.sub_method.id, 'text': item.sub_method.name})
return HttpResponse(json.dumps({'err': 'nil', 'results': results, 'results2': results2}), content_type='application/json')
I would like to import into my dropdown field values from results2 (python file) when I have sel_val is empty :
if (sel_val === '') {
...
}
So how I could rewrite this part :
if (sel_val === '') {
console.log('none sorting group');
$("select#id_method-sub_method").empty();
$("select#id_method-sub_method").append('<option value=""> test </option>'); //here add list of all submethods
return;
}
Like this :
if (sel_val === '') {
$("select#id_method-sub_method").empty();
for (var i = 0; i < result['results2'].length; i++) {
$("select#id_method-sub_method").append('<option value="' + result['results2'][i].id + '">' + result['results2'][i].text + '</option>'); //here add list of all submethods
}
return;
}
with for loop and append all elements from results2 to my dropdown field ? The issue is actually with result['results2']
Hopfully it's readable and understandable.
Thank you !
EDIT :
As #Darren Crabb said, it's a possible out of scope.
So I rewrote my JS like this :
if (!sel_val) {
reset_select('id_method-sub_method');
$("select#id_method-sub_method").empty();
var all = "{{ results2 }}";
for (var i = 0; i < all.length; i++) {
$("select#id_method-sub_method").append('<option value="' + all[i].id + '">' + all[i].text + '</option>'); //here add list of all submethods
}
return;
}
And I defined in my python file : context['results2'] = SubMethod.objects.all()
I get this :

recursively object to ul list and add class with index in javascript

I have a working recursive function that creates an <ul> list from an object, it works fine,
my problem is that I want to keep track of the index, and add it as class to <li> elements,
I need that the "index count system" will count in a particular way, and this is the output that I want:
class0
class0_0
class0_0_0
class0_0_1
class0_1
class0_1_0
class0_1_1
class1
class1_0
class1_0_0
class1_0_1
class1_1
class1_1_0
class1_1_1
by increasing, restarting and have maybe multiple "index count" variables in the recirsive function
This is what I'm trying, but I still can't figure out where to properly set, increase, reset the counters to achieve that result..
var i = 0;
function object2ul(data) {
var json = "<ul>";
for(var key in data) {
json = json + "<li>" +'<b>'+i+'</b>'+ key; i++;
if(typeof data[key] == 'object') {
json = json + object2ul(data[key]);
}else{ i=0;
json = json + '<ul><li>'+ data[key]+'</li></ul>';
}
json = json + "</li>";
}
return json + "</ul>";
}
document.body.innerHTML = object2ul(object);
In this example I omitted to set the classes avoiding to complicate the function
DEMO
Something like this?
var object = {
root0: {
child0: {
leaf: 'text',
leaf: 'text'
},
child1: {
leaf: 'text',
leaf: 'text'
}
},
root1: {
child0:{
leaf: 'text',
leaf: 'text'
},
child1: {
leaf: 'text',
leaf: 'text'
}
}
};
var i = 0;
function object2ul(data, prefix) {
prefix = prefix || '0'; // default
var json = "<ul>";
var childIndex = 0;
for(var key in data) {
json = json + "<li>" +'<b>'+i+'</b>'+ key; i++;
if(typeof data[key] == 'object') {
json = json + object2ul(data[key], prefix + '_' + childIndex);
}else{ i=0;
json = json + '<ul><li>'+ data[key]+'---(' + prefix + ')</li></ul>';
}
json = json + "</li>";
childIndex++;
}
return json + "</ul>";
}
document.body.innerHTML = object2ul(object);
To get the kind of indexing you want, you are going to have to use Object.keys. The following should work for an arbitrary object:
var testObj = { a: { b: '2', d: '5', e: { f: '3' } }, c: '3' };
var indexes = [];
var object2ul = function (data) {
var keys = Object.keys(data);
var json = "<ul>";
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
indexes.push(i);
json += "<li>" + "<b>" + indexes.join('_') + "</b>" + key;
if (typeof(data[key]) === 'object') {
json += object2ul(data[key]);
} else {
json += "<ul><li>" + data[key] + "</li></ul>";
}
json += "</li>";
indexes.pop();
}
return json + "</ul>";
}
document.body.innerHTML = object2ul(testObj);
Here's it in action:
JSFiddle

Access object property in array of objects

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!

Getting index number of element of array

I have json with array of objects in it. I build my page depends on elements in this array. If there is no duplicate values of key called points, i render page with some info and description, using value of points to find this element in array. However if i have 2 and more duplicate values of key called points i render list of these elements. In this case i cant use value of points to find element in array. I know i can use index number of array element, and then pass it as parameter to my function that find and build info and description, but i'm not sure how to do that. How do i get index number of element in array?
P.S. Can provide my code if needed
Code that i'm using
var allRewards = null;
$("#reward").live('pagecreate', function(e) {
var request = $.ajax({
type: "GET",
url: "example.com/test.json"
dataType: "json",
error: function (data, textStatus){
console.log( "it`s error" );
console.log( status );
console.log( data );},
success: function (data, textStatus){
console.log( "success" );
console.log( status );
console.log( data );
}
})
request.success(function(data, textStatus){
var lis = "";
var arr = [];
var iter = 0;
allRewards = data
$.each(data.rewards, function(key, val){
if ($.inArray(val.points, arr) == -1)
{
lis += "<div data-points='"+ val.points +"'align=CENTER class = 'rewards-block ui-block-" + String.fromCharCode(97 + iter%3) + "'><a href ='#' class ='ui-link-inherit' onclick='showreward("+val.points+")'><img src ='./img/reward-icon.png'/><span>" + val.points + " pts</span></a></div>";
arr.push(val.points);
iter += 1;
}
});
$("#rewards_table").html(lis);
})
});
function showreward(point)
{
$.mobile.changePage('show-rewards.html')
console.log(allRewards);
$("#showrewards").live('pagecreate', function(e) {
var items = "";
var arr = [];
var counter = 0;
var result = $.grep(allRewards.rewards, function(e){ return e.points == point; });
if (result.length > 1)
{
$.each(result, function(key, val){
items += "<div style='color:white;'>" + val.title + "</div>"
console.log(val.title);
})
}
else if (result.length == 1)
{
// $.each(result, function(key, val){
// items += "div style='color:white;'"+ val.points + "></div>"
// console.log(val.points);
// })
$.each(result, function(key, val){
items += "<div style='background:white; padding:5px 5px 20px 5px;'><img style ='float:right; width:45%; margin-top:22px; padding: 0 0 10px 10px;' src ='" + val.main_photo_url + "'/><h3>"+ val.title + "</h3><p>" + val.description + "</p><p style='font-weight:bold; font-size:13px;'>Reedem below for " + val.points + " Zingle Points</p><table class='pagemenu' style='width:200px;'><tr><td class='width_5'><input type='submit' data-theme='w' value='Reedem Now' data-inline='true'></td><td><a data-role='button' data-icon='pagemenu-share' data-iconpos='notext' href='index.html' data-shadow='false' data-corners='false'></a></td></tr></table></div>"
});
}
console.log(items);
$("#rewards-list").html(items);
});
}
I think you're looking for Array.indexOf.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
PS. This is available in Underscore as _.indexOf.

Categories

Resources