Access object property in array of objects - javascript

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!

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

How to loop throught objects with arrays as properties

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/

printing the json array from certain indexes

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

JavaScript foreach Key Value array

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

How do I loop through a JSON list?

I have multiple items in my JSON list. I want to loop through it and display it on my page. I can't seem to get to the next object though.
{
"room":[
{"campusName":"A",
"buildingCode":"B",
"roomNumber":"208",
"times":["7-8", "9-10"]
}],
"room2":[
{"campusName":"C",
"buildingCode":"D",
"roomNumber":"208",
"times":["7-8", "9-10"
]}
]}
$(document).ready(function(){
$.getJSON("data.json", function(data){
$.each(data.room, function(){
for(var i = 0; i < data.length; i++){
$("ul").append("<li>campus: "+this['campusName']+"</li><li>building: "+this['buildingCode']+"</li><li>times: "+this.times+"</li>");
}
});
});
});
Try this
var list = '';
$.each(data, function (i, root) {
$.each(root, function (i, el) {
list += "<li>campus: " + this.campusName + "</li><li>building: " + this.buildingCode + "</li><li>times: " + this.times.join(' ') + "</li>";
});
});
$('ul').html(list);
Example
If root's has only one element in array
var list = '';
$.each(data, function (i, root) {
list += "<li>campus: " + root[0].campusName + "</li><li>building: " + root[0].buildingCode + "</li><li>times: " + root[0].times.join(' ') + "</li>";
});
$('ul').html(list);
Example
$.each(data, ..) --> Each element will be:
"room":[
{"campusName":"A",
"buildingCode":"B",
"roomNumber":"208",
"times":["7-8", "9-10"]
}]
Then, this[0] will provide the object you need to construct your li:
$.each(data, function(){
$("ul").append("<li>campus: "+this[0]['campusName']+"</li><li>building: "+this[0]['buildingCode']+"</li><li>times: "+this[0].times+"</li>");
});
Fiddle

Categories

Resources