I'm working on an add-in for excel 2016 using the javascript API. I can successfully get the range into an array and get the values to show in console.log. I've also been able to get the values into a JSON array using JSON.stringify();
I need to manipulate the array to remove the empty values ("").
Can this be accomplished by using regular javascript array methods?
I'm thinking I can display the results back into a different worksheet using a similar approach like i did with var shWk
Here are some snippets of what I'm trying to do:
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
//document.getElementById("date").innerHTML = Date("MAR 30 2017");
$('#deleteTab').click(deleteTab);
$('#preview').click(preview);
$('#publish').click(publish);
});
};
function preview() {
Excel.run(function(ctx) {
//getting the colname from a date range in B2
var colName = ctx.workbook.worksheets.getItem('preview').getRange("B2");
colName.load('values');
return ctx.sync().then(function() {
//converting colname value to string for column name
var wkN = (colName.values).toString();
// displaying on the task pane
document.getElementById("tst").innerText = wkN;
// testing to confirm i got the correct colname
var shWk = ctx.workbook.worksheets.getItem('preview').getRange("B3");
shWk.values = colName.values;
//building the column connection by setting the table name located on a different worksheet
var tblName = 'PILOT_ZMRP1';
var tblWK = ctx.workbook.tables.getItem(tblName).columns.getItem(wkN);
//loading up tblWK
tblWK.load('values');
return ctx.sync().then(function(){
//this is where my question is:
var arry = tblWK.values;
for (var i=0; i < tblWK.length; i++){
if (tblWK.values !== ""){
arry.values[i][0]) = tblWK.values[i][0]
};
};
console.log(arry.length); //returns 185
console.log (arry.values);//returns undefined
tblWK.values = arry;
var tblWeek = tblWK.values;
console.log(tblWeek.length);//returns 185
console.log(tblWK.values);//returns [object Array] [Array[1],Array[2]
})
});
}).catch(function (error) {
console.log(error);
console.log("debug info: " + JSON.stringify(error.debugInfo));
});
}
What am I missing? Can you point me to some resources for javascript array handling in the specific context of office.js?
I want to thank everyone for the time spent looking at this question. This is my second question ever posted on Stack Overflow. I see that the question was not written as clear as it could've been. What i was trying to achieve was filtering out the values in a 1D array that had "". The data populating the array was from a column in a separate worksheet that had empty values (hence the "") and numeric values in it. the code below resolved my issue.
//using .filter()
var itm = tblWK.values;
function filt(itm){
return itm != "";
}
var arry = [];
var sht = [];
var j=0;
var s=0;
arry.values = tblWK.values.filter(filt);
//then to build the display range to show the values:
for (var i=0; i < itm.length-1; i++) {
if (tblWK.values[i][0]){
var arry; //tblWK.values.splice(i,0); -splice did not work, maybe my syntax was wrong?
console.log("this printed: "+tblWK.values[i][0]);
var cl = ('D'+i); //building the range for display
j++; //increasing the range
s=1;//setting the beignning range
var cll = cl.toString();//getRange() must be a string
console.log(cll);//testing the output
}
}
//using the variable from the for loop
var cl = ('D'+s+':D'+j);
var cll = cl.toString();
console.log(cll);//testing the build string
sht = ctx.workbook.worksheets.getItem('Preview').getRange(cll);
sht.values = arry.values; //displays on the preview tab
console.log (arry.values); //testing the output
The question was probably easier said by asking what vanilla javascript functions does office.js support. I found a lot help reading Building Office Add-ins using Office.js by Micheal Zlatkovsky and by reading the MDN documentation as well as the suggested answer posted here.
Regards,
J
I'm not sure what this check is trying to achieve: tblWK.values !== "". .values is a 2D array and won't ever be "".
For Excel, the value "" means that the cell is empty. In other words, if you want to clear a cell, you assign to "". null value assignment results in no-op.
You can just fetch the values form the array that contains null by using for each and can can push the null values into another array.
My Javascript is like this :
<script type="text/javascript">
var priceJson = '[{"#attributes":{"Code":"SGL","Total":"400000"},"DayPrice":{"Date":"2016-05-26","Rate":"400000"}},{"#attributes":{"Code":"DBL","Total":"200000"},"DayPrice":{"Date":"2016-05-26","Rate":"200000"}}]';
console.log(priceJson);
var priceObject = JSON.parse(priceJson);
console.log(priceObject);
if(priceObject.DayPrice.Rate)
priceObject = [priceObject];
else
priceObject = priceObject;
console.log(priceObject);
var priceJson = JSON.stringify(priceObject);
console.log(priceJson);
var countRoomType = priceObject.length;
for(var i=0; i<countRoomType; i++){
console.log(priceObject[i].DayPrice.Date);
console.log(priceObject[i].DayPrice.Rate);
}
</script>
Demo (See in console) : https://jsfiddle.net/oscar11/wsqdha8w/1/
Variable priceJson has a dynamic value. The value can be one single instance of data or can be an array of data. If the value contains 1 data then I convert into a data array like this:
if(priceObject.DayPrice.Rate)
priceObject = [priceObject];
But, in console there is the following error: TypeError: priceObject.DayPrice is undefined
Any solutions to solve my problem?
Judging by your error message, you need to check the existance of DayPrice also.
if( priceObject.DayPrice && priceObject.DayPrice.Rate )
This if condition has two steps.
First it checks if DayPrice exists,
Second it checks if DayPrice.Rate exists
It won't check second condition if first one fails
I'm newbie to the Javascript/Jquery world.
I have a div with several links and i want to collect the url's .
Then i want to extract from those href's the last 9 characters (actually i wish to optimize it and collect the digits independently the length at the end of each string).I tried to extract them with the slice() method but it does not work.
In console the error is
Object doesn't support property or method 'slice'
Can i convert the object to a string ? Your help is appreciated !
The code is the following
$(document).ready(function(){
var $posts= $('a.entry_title').each(function(){
$(this).attr('href');
});
var posts1 = $posts[0].slice(-9);
var posts2 = $posts[1].slice(-9);
var posts = ["MyURL"+ posts1,"MyURL"+posts2]
$('#div1').load(posts[0] + " .shadow3");
$('#div2').load(posts[1] + " .shadow3");
});
</script>
You see Object doesn't support because $.each returns a jQuery object.
Use .map() instead because it returns an array on which slice would work
var $posts= $('a.entry_title').map(function(){
return $(this).attr('href');
});
Result would be
["link1", "link2", "link3"....] // just a sample
If you wish to get an array of hrefs with last nine characters of each link you can use map this way
var $posts= $('a.entry_title').map(function(){
return $(this).attr('href').slice(-9); // or you can do your own magic
});
Result would look like this
["k1", "k2", "k3"....] // after slicing the words
Try next one:
var hrefs = []; // list of collected and sliced hrefs.
var $posts= $('a.entry_title').each(function() {
// slice & push each href into list.
hrefs.push($(this).attr('href').slice(-9));
});
console.log('href list:', hrefs); // control result.
var posts = ["MyURL"+ hrefs[0],"MyURL"+hrefs[1]]
I have following json data coming from server in which i want to extract LimitClass and LimitClassID and store their values in respective arrays.
{
"ErrorDesc":"",
"ErrorCode":"",
"LimitClassList":"[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]"
}
Here is the code I have tried :
var list = data.LimitClassList;
var arrayLimitClass = [];
var arrayLimitClassId = [];
for(var i in list) {
arrayLimitClass.push(list[i].LimitClass);
arrayLimitClassId.push( list[i].LimitClassId);
}
alert(list);
alert(arrayLimitClass);
alert(arrayLimitClassId);
List variable has following result when I alert it:
[{\"LimitClass\":\"L16\\n\",\"LimitClassId\":\"32900\\n\"},{\"LimitClass\":\"28febL0\\n\",\"LimitClassId\":\"31901\\n\"},{\"LimitClass\":\"L14\\n\",\"LimitClassId\":\"31900\\n\"},{\"LimitClass\":\"L17\\n\",\"LimitClassId\":\"32950\\n\"},{\"LimitClass\":\"L15\\n\",\"LimitClassId\":\"31950\\n\"},{\"LimitClass\":\"L0\\n\",\"LimitClassId\":\"21901\\n\"},{\"LimitClass\":\"L4\\n\",\"LimitClassId\":\"23000\\n\"},{\"LimitClass\":\"OTC Send\\n\",\"LimitClassId\":\"30901\\n\"},{\"LimitClass\":\"L2\\n\",\"LimitClassId\":\"22900\\n\"},{\"LimitClass\":\"L12\\n\",\"LimitClassId\":\"28900\\n\"},{\"LimitClass\":\"L6\\n\",\"LimitClassId\":\"23900\\n\"},{\"LimitClass\":\"L1\\n\",\"LimitClassId\":\"25900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"29900\\n\"},{\"LimitClass\":\"L7\\n\",\"LimitClassId\":\"24900\\n\"},{\"LimitClass\":\"L8\\n\",\"LimitClassId\":\"26900\\n\"},{\"LimitClass\":\"L10\\n\",\"LimitClassId\":\"27900\\n\"},{\"LimitClass\":\"L13\\n\",\"LimitClassId\":\"30900\\n\"},{\"LimitClass\":\"UatTesting123\\n\",\"LimitClassId\":\"32901\\n\"}]
But I am getting dots (.) when I alert arrayLimitClass and arrayLimitClassId. What am I doing wrong in extracting rows of json Object?
"LimitClassList":"[{\"LimitClass\":\"L1....]"
^ ^
LimitClassList is a string, not an array. Make it so it is an actual array, than your code should work. There should be no reason to have to parse it again.
The value below data.LimitClassList is itself a String containing JSON. You have to decode this first.
var list = JSON.parse( data.LimitClassList );
var arrayLimitClass = [];
var arrayLimitClassId = [];
// ...
This is more or less a workaround. You should have a look at your server code and fix the encoding error there!
var formRules = $(this).data('rules');
var formValues = $(this).data('values');
if(formRules || formValues){
var rulesArray = formRules.split(',');
var valuesArray = formValues.split(',');
for(var i=0; i < rulesArray.length; i++){
//alert(rulesArray[i]);
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
}
}
else{
return false;
}
This throws an error like following
Error: TypeError: $.validationEngine.defaults.rulesArray is undefined
Source File: http://localhost:8380/javascript/jquery.validationEngine.js
Line: 2092
I cannot find the problem with this code.Any help is welcome
EDIT:
I am trying to set the global options eg:scroll using the for loop.
The formRules string will have these options comma seperated and the corresponding values in the formValues string.
So i am expecting it to come like $.validationEngine.defaults.scroll = true;
change this line
$.validationEngine.defaults.rulesArray[i] = valuesArray[i];
to this
$.validationEngine.defaults[rulesArray[i]] = valuesArray[i];
rulesArray is not a child of $.validationEngine.defaults. The values stored in your rulesArray are. The syntax in my second code block references everything properly.
This is called Bracket Notation, a way to get an object's property using any sort of valid calculation (like rulesArray[i], or "myStringPropertyName"). see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Member_Operators for other methods.