Automatically push / nest object within a parent object in JavaScript - javascript

I am currently working on an excel like behaviour for some task.
All "tr"s are bound to the variable $test
var $test = $('tbody tr');
Now I use the jQuery .each function to run throuhg all trs and collect its relevant contents like this :
$test.each(function(index, element){
var $row_id = $(this).data("rowid");
var status = $(this).find('#status option:selected').val();
var ma_name = $(this).find('#ma-name').val();
var datum = $(this).find('#datum').val();
var firmenname1 = $(this).find('#firmenname1').val();
var firmenname2 = $(this).find('#firmenname2').val();
var limit = $(this).find('#limit').val();
var gruppe_kredit = $(this).find('#gruppe_kredit').val();
var omv_kdnr = $(this).find('#omv_kdnr').val();
var sap_kdnr = $(this).find('#sap_kdnr').val();
var fos = $(this).find('#fos').val();
var hga_kdnr = $(this).find('#fos').val();
var pushObj = {row_id: $row_id,....};
});
Since the pushObject gets greated and stuffed with content each time the each function gets executed I need a way to "push" this object into a parent object which I can later use with AJAX.
The behaviour I'd wish for would be like this:
var parentObj = {};
$.each(function(){
// in each run the newly created object gets nested into the parentObject which results in the parent object having X-childObjects
});
So after, lets say 5 each runs, the parentObj should contain : [0],[1],...,[4] objects.
Could anyone guide me throuhg that process ?

Try this solution by storing pushObj inside array variable like so :
// add here
var parentObj = [];
$test.each(function (index, element) {
var $row_id = $(this).data("rowid");
var status = $(this).find('#status option:selected').val();
var ma_name = $(this).find('#ma-name').val();
var datum = $(this).find('#datum').val();
var firmenname1 = $(this).find('#firmenname1').val();
var firmenname2 = $(this).find('#firmenname2').val();
var limit = $(this).find('#limit').val();
var gruppe_kredit = $(this).find('#gruppe_kredit').val();
var omv_kdnr = $(this).find('#omv_kdnr').val();
var sap_kdnr = $(this).find('#sap_kdnr').val();
var fos = $(this).find('#fos').val();
var hga_kdnr = $(this).find('#fos').val();
var pushObj = {
row_id: $row_id,
....
};
// add here
parentObj.push(pushObj);
});
// later on here access parentObj variable

Related

Google Form creates Google Slides from template Script

I have a script that on Form submit takes the data from the spreadsheet and creates a copy of a template and populates the google docs. I am trying to accomplish the same thing from google form to google slides.
First script I use for the google forms to google docs. The second script is my attempt of using the same principles and applying to google slides. My issue is I'm getting an error saying TypeError: values.forEach is not a function (line 109, file "Code") in relation to values.forEach(function(page). Any suggestions on how I could go about solving this?
Google Form to Google Sheets
function autoFillGoogleDocFromForm(e) {
var timestamp = e.values[0];
var address = e.values[1];
var image = e.values[2];
var price = e.values[3];
var summary = e.values[4];
var type = e.values[5];
var year_built = e.values[6];
var bed = e.values[7];
var bath = e.values[8];
var home_size = e.values[9];
var lot_size = e.values[10];
var occupancy = e.values[11];
var templateFile = DriveApp.getFileById("xxxxxxxx");
var templateResponseFolder = DriveApp.getFolderById("yyyyyyyyyy")
var copy = templateFile.makeCopy( address , templateResponseFolder);
var doc = DocumentApp.openById(copy.getId())
var body = doc.getBody();
body.replaceText("{{address}}", address);
body.replaceText("{{price}}", price);
body.replaceText("{{summary}}", summary);
body.replaceText("{{type}}", type);
body.replaceText("{{year_built}}", year_built);
body.replaceText("{{beds}}", bed);
body.replaceText("{{baths}}", bath);
body.replaceText("{{home_size}}", home_size);
body.replaceText("{{lot_size}}", lot_size);
body.replaceText("{{occupancy}}", occupancy);
doc.saveAndClose;
}
Google Form to Google Slides
function generateLandingPagesReport(){
var dataSpreadsheetUrl = "https://docs.google.com/spreadsheets/xxxxxxxxx/edit"
var Presentation_ID = "xxxxxxxxxxxxxx";
var ss = SpreadsheetApp.openByUrl(dataSpreadsheetUrl);
var deck = SlidesApp.openById(Presentation_ID);
var sheet = ss.getSheetByName('Sheet1');
var values = sheet.getRange('A1:J17').getValues;
var slides = deck.getSlides();
var templateSlide = slides[1];
var presLength = slides.length;
values.forEach(function(page){
values.forEach(function(page){
if(page[0]){
var landingPage = page[0];
var sessions = page[1];
var newSessions = page[2];
}
templateSlide.duplicate(); // duplicate the template page
/*slides = deck.getSlides(); // update the slides array for indexes and length*/
newSlide = slides[2]; // declare the new page to update
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}', landingPage);
shape.getText().replaceAllText('{{sessions}}', sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
});
presLength = slides.length;
newSlide.move(presLength);
//end our condition statement
}); //close our loop of values
//remove template slide
templateSlide.remove();
});
}
You're missing the parenthesis when calling the getValue() method.
Change this:
var values = sheet.getRange('A1:J17').getValues;
To this:
var values = sheet.getRange('A1:J17').getValues();
Not exactly what I was looking for but this uses the first Row to identify the tag inside the Google slides template like {{title}} and replaces that with the value in the second row of the sheet
function createPresentation() {
var templateFile = DriveApp.getFileById("1YVEA4WtU1Kf6nZRgHpwnKBIR-V6rRN6s9zCdOQDkWNI");
var templateResponseFolder = DriveApp.getFolderById("1k7rcfXODij4o4arSULuKZUHbit1m_X64");
var copy = templateFile.makeCopy("New" , templateResponseFolder);
var Presentation = SlidesApp.openById(copy.getId());
var values = SpreadsheetApp.getActive().getDataRange().getValues();
values.forEach(function(row) {
var templateVariable = row[0];
var templateValue = row[1];
Presentation.replaceAllText(templateVariable, templateValue);
});
}
After you have copy the template page, you work on it and try to do replace.
However, change may be pending such that newSlide = slides[2]; give undefined.
You may need to try saveAndClose() before performing any actions.
templateSlide.duplicate(); // duplicate the template page
/*slides = deck.getSlides(); // update the slides array for indexes and length*/
/* flush the presentation */
deck.saveAndClose();
deck = SlidesApp.openById(Presentation_ID);
slides = deck.getSlides();
newSlide = slides[2]; // declare the new page to update
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}', landingPage);
shape.getText().replaceAllText('{{sessions}}', sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
});

JSON-array and forEach issue

So... The problem I have according to the console is:
"Uncaught TypeError: Cannot read property 'title' of undefined
at custom.js:42, at Array.forEach (), at custom.js:39"
How is "title" undefined? What's wrong with my .forEach? (sad noises)
Example of first of six objects in the JSON-array I've built:
var newReleases = [
{
"title":"Honor - Defending the motherland",
"author":"Mark Thomas",
"genre":"Fiction",
"description":"In legislation and formal documents the suffix shire was generally not used: for example, Bedfordshire was referred to as the administrative county of Bedford and the Northamptonshire council as the county council of Northampton.The 1888 Act did not contain a list of administrative counties: it was not until 1933 and the passing of a new Local Government Act."},
For loop with forEach function:
for (var i = 0; i < 6; i++){
newReleases.forEach (function (newReleases) {
var bookTitle = document.getElementsByClassName('card-header')
var t = document.createTextNode(newReleases[i].title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')
var a = document.createTextNode(newReleases[i].authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle");
var genre = document.createTextNode(newReleases[i].genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text');
var p = document.createTextNode(newReleases[i].description);
cardDescr.appendChild(p);
}) //end of forEach
} // end of for-loop
Use either for or forEach(), not both.
for (var i = 0; i < newReleases.length; i++) {
var bookTitle = document.getElementsByClassName('card-header')[0]
var t = document.createTextNode(newReleases[i].title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')[0]
var a = document.createTextNode(newReleases[i].authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle")[0];
var genre = document.createTextNode(newReleases[i].genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text')[0];
var p = document.createTextNode(newReleases[i].description);
cardDescr.appendChild(p);
}
or
newReleases.forEach(function(release) {
var bookTitle = document.getElementsByClassName('card-header')[0]
var t = document.createTextNode(release.title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')[0]
var a = document.createTextNode(release.authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle")[0];
var genre = document.createTextNode(release.genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text')[0];
var p = document.createTextNode(release.description);
cardDescr.appendChild(p);
});
When you use forEach() you don't need to subscript the array variable, you just use the parameter to the callback function.

Not appending the desired output in jquery

I have the following (very incomplete) code that I want to eventually be a shopping cart using jquery.
This is code for loading items remotely from a json file and parsing them into Html using jquery.
$(document).ready(function () {
"use strict";
// Download the content
var head = $("<h1>Aisan Market</h1>");
var dl = $("<dl>");
$("body")
.append(head)
.append(dl)
for (var i = 0; i <shop.length; i++) {
var item = shop[i];
var dt=$("<dt>").text(item.itemId)
var dt1 = $("<dt>").text(item.name)
var dd = $("<dd>").text(item.price)
var button = $("<button>buy</button>");
dl
.append(button)
.append(dt)
.append(dt1)
.append(dd);
}
Here I'd like to have on a button click to walk the dom tree to the correct item id,item name and price and append that to the cart.but it's not doing that.It's writing the id number repeating it and writing 0.
var cart = $("<div>cart<div>");
$("body").append(cart);
var total = 0;
$("button").on("click", function () {
var a = $(this);
var prev = a.next("dt").text();
var b = $(this);
var prev1 = b.next("dt").text();
var c = $(this);
var prev2 = c.next("dd").text();
total += prev2;
cart
.append(prev)
.append(prev1)
.append(total);
});
});
Where am I going wrong.
Thanks a lot.

Nested Loop Javascript

can someone please let me know, whats wrong with the format of my nested loop. i dont seem to be getting it to loop correctly. the values that are the same are not being generated together.
for (var field in Itemlist) {
for (var field in EstItems){
console.log(Itemlist[field].item_id, EstItems[field].zoho_id);
if (EstItems[field].zoho_id == Itemlist[field].item_id) {
console.log("We are In");
var id = EstItems[field].itemID;
var itemID = EstItems[field].zoho_id;
var barcode = EstItems[field].barcode;
//var EstBarcode = EstItems[field].itemID;
var description = EstItems[field].description;
var cost = EstItems[field].cost;
var shippingCost = "500";
var clearingCharges = "";
var quantityOrdered = 1;
//var quantityRecvd = EstItems[field].itemID;
//var quantityRTD = EstItems[field].itemID;
var selected = 0;
var totalcost = (cost*quantityOrdered)+parseFloat(shippingCost);
var categoryID = 0;
}
}
}
You have a scope problem introduced by overwriting a previous variable.
for (var field in Itemlist) {
// `field` here is a property from ItemList
for (var field in EstItems){
// `field` here is a property from EstItems
// Any attempt to access the `field` var from the outer loop will fail, as it has been overwritten.
}
}
Rename field for either loop.

How to make this jQuery code more simple and effective

I have follow two functions here which working great!
As you can see these two functions are almost the same, except the code which comes below the last comment in each function.
How do I make that more simple. Could I make a code-"holder" - Where I only include a part of a code from another file? So I don't have too have the "same" code in each functions?
Should I use some kind of classes or? - I have never worked with classes.
/// Function (add_new_field)
$(document).on("click", '.add_new_field', function(e) {
e.preventDefault();
var flex0 = $(this);
var flex1 = $(this).parent().closest('div');
var flex2 = $(flex1).parent().closest('div');
var flex3 = $(flex2).parent().closest('div');
var flex4 = $(flex3).parent().closest('div');
var flex5 = $(flex4).parent().closest('div');
var flex6 = $(flex5).parent().closest('div');
/*console.log(
' -> WrapID:'+flex6.attr('id')+
' -> accordionContentID:'+flex5.attr('id')+
' -> acContentBoxID:'+flex4.attr('id')+
' -> acChildBoxID:'+flex3.attr('id')+
' -> acBabyBoxID:'+flex2.attr('id')+
' -> SecondID:'+flex1.attr('id')+
' -> FirstID:'+flex0.attr('id')
);*/
var wrapID = flex6.attr('id'); // wrapID
var accordionContentID = flex5.attr('id');
var acContentBoxID = flex4.attr('id'); // sharedID
var acChildBoxID = flex3.attr('id'); // langID
var acBabyBoxID = flex2.attr('id'); // langID
var SecondID = flex1.attr('id'); // OLD : AddLangBoxID
var FirstID = flex0.attr('id'); // OLD : add_new_fieldID
// there is a lot more code here...
)};
/// Function (del_field)
$(document).on("click", '.del_field', function(e) {
e.preventDefault();
var flex0 = $(this);
var flex1 = $(this).parent().closest('div');
var flex2 = $(flex1).parent().closest('div');
var flex3 = $(flex2).parent().closest('div');
var flex4 = $(flex3).parent().closest('div');
var flex5 = $(flex4).parent().closest('div');
var flex6 = $(flex5).parent().closest('div');
var wrapID = flex6.attr('id'); // wrapID
var accordionContentID = flex5.attr('id');
var acContentBoxID = flex4.attr('id'); // sharedID
var acChildBoxID = flex3.attr('id'); // langID
var acBabyBoxID = flex2.attr('id'); // langID
var SecondID = flex1.attr('id'); // OLD : AddLangBoxID
var FirstID = flex0.attr('id'); // OLD : add_new_fieldID
// there is a lot more code her
)};
How could I make something like this.
/// I want to include this code into the functions. So I don't have to write it twice.
var flex0 = $(this);
var flex1 = $(this).parent().closest('div');
var flex2 = $(flex1).parent().closest('div');
var flex3 = $(flex2).parent().closest('div');
var flex4 = $(flex3).parent().closest('div');
var flex5 = $(flex4).parent().closest('div');
var flex6 = $(flex5).parent().closest('div');
var wrapID = flex6.attr('id'); // wrapID
var accordionContentID = flex5.attr('id');
var acContentBoxID = flex4.attr('id'); // sharedID
var acChildBoxID = flex3.attr('id'); // langID
var acBabyBoxID = flex2.attr('id'); // langID
var SecondID = flex1.attr('id'); // OLD : AddLangBoxID
var FirstID = flex0.attr('id'); // OLD : add_new_fieldID
Thank you.
If you want to do something like classes in javascript, your best bet is to use prototyping, since javascript doesn't have classes.
In this case, I'm not sure what your code does, so prototyping might not be the best answer. Your other option is to encapsulate all of your variable definitions in another function, and call that function in both of your click functions. It would return an object with attributes, rather that a bunch of vars.
var myVarFn = function(){
var returnObject = {};
returnObject.flex0 = $(this);
returnObject.flex1 = $(this).parent().closest('div');
...
returnObject.wrapID = flex6.attr('id'); // wrapID
...
return returnOBject
}
And to use it in click, with this defined the same as in the scope of the click function:
$(document).on("click", '.del_field', function(e) {
var dataObject = myVarFn.call(this);
//Other code
};
And in the other click event,
$(document).on("click", '.add_new_field', function(e) {
var dataObject = myVarFn.call(this);
//Other code
};
You will have to modify your other code to use dataObject.flex0 instead of flex0 and so on.
Create a global object
var allId = new Object();
And a function that can be called whenever needed..
function getAllIDs(el) {
var id = ["wrapID", "accordionContentID", "acContentBoxID", "acChildBoxID", "acBabyBoxID", "SecondID", "FirstID"];
var flex;
for (var i = 0; i <= 6; i++) {
if (i == 0) {
flex = $(el).parent().closest('div');
} else {
flex = $(flex).parent().closest('div');
}
allId.id[i] = $(flex).parent().closest('div').attr('id');
}
}
Further, on jQuery event you can call getAllIDs function
$(document).on("click", '.add_new_field', function (e) {
e.preventDefault();
getAllIDs(this);
});
More details about javascript objects

Categories

Resources