My local storage looks like this
{"data":[[0,"Post1","Text1","2016-12-16T11:01:00.000Z"],[1,"Post2","Text2","2016-12-20T14:00:00.000Z"]],[3,"Post3","Text3","2016-12-25T13:00:00.000Z"]]}
How can I delete only one item in the array?
I have tried with this, where postid is the array index I want to delete.
var postid = 1
var info = JSON.parse(localStorage.getItem("rp_data"));
var obj = [];
for(var i = 0; i < info.data.length; i++){
var data = info.data[i];
if(data === postid){
info.splice(i, 1);
}
}
localStorage.setItem("rp_data", JSON.stringify(data));
So the if part is wrong I guess!?
Any input appreciated, thanks.
UPDATE
So with this I can remove one of the posts in the array, where the first item in the array is equal to my postid, so if the postid=1 it will remove the second post in the array.
//var postid = $$(this).attr('data-id');
//postid=parseInt(postid)
postid=1
var info = JSON.parse(localStorage.getItem("rp_data"));
//remove object
for(var i = 0; i < info.data.length; i++){
var data = info.data[i][1];
myApp.alert(data);
if(i === postid){
myApp.alert(i);
info.data.splice(i, 1);
}
}
localStorage.removeItem("rp_data");
localStorage.setItem("rp_data", JSON.stringify(info));
So I have 1 more problems.
If I use postid=1 as above it works and it creates a new local storage with the right values. But if get the value from my form and then try to convert the string to a number it stops working.
This does not work, like it is not converting the string to a number?
var postid = $$(this).attr('data-id');
postid=parseInt(postid)
So why is this not converting it to a number?
Since the items in the array are JSON objects, you cannot compare the object to postid. You should use indexOf. You also don't want to splice the index. This should be the object or item in this case. If you want to remove the item in the object, you would have to iterate through the object as well. So this would be a nested loop.
//remove object
for(var i = 0; i < info.data.length; i++){
var data = info.data[i];
if(i === postid){
info.data.splice(data, 1);
}
}
//remove item in object
for(var i = 0; i < info.data.length; i++){
if(i == postid){
for(var j = 0; j < info.data[i].length; j++){
var item = info.data[i][j];
info.data[i].splice(item,1);
}
}
}
Related
How to grab the contentID and content title add it within an array and have it used in the URL of API 2
if i use the code below for section title and sectionid it is working because it is not in an nested array but for the contentid and contenttitle it is not working as it is in a nested array.
In the API 1 test tab i have:
for (i = 0; i < resultCount; i++) {
var id = jsonData[i].contents[0].contentId;
var modelString = jsonData[i].contents[0].contentTitle;
console.log(id)
console.log(modelString)
if (modelString.includes(“APIAUTOMATIONcontent”) || modelString.includes(“Testcontent”) || modelString.includes("{{POST-NewSlide}}") || modelString.includes(“stringcontent”)) {
hasDelete.push(id);
// (id) - this creates an integer (int)
// "announcementId": id, (creating object)
// "hasDelete": modelString.includes("Delete") || modelString.includes("Test")
// });
} else {
doesntHaveDelete.push(id)
// "announcementId": id
// });
}
}
// Check that each object in response contained keyword and length matches from test
pm.test(Number of Content that has APIAUTOMATIONcontent or Test ready to be deleted = ${hasDelete.length} out of Total ${resultCount} , function() {
console.log(hasDelete);
console.log(doesntHaveDelete);
pm.expect(hasDelete.length);
});
pm.collectionVariables.set(‘deletesections’, JSON.stringify(hasDelete));
Like you're iterating over each section in your response body, you also need to iterate over the contents array, you can do it like below:
for (i = 0; i < resultCount; i++) {
contentCount = jsonData[i].contents.length;
for (j = 0; j < contentCount; j++) {
let content = jsonData[i].contents[j];
console.log(content.contentId);
console.log(content.sectionId);
console.log(content.contentTitle);
console.log(content.pdfLink);
console.log(content.videoLink);
console.log(content.sortOrder);
}
}
----- BACKGROUND ----- In Google Sheets/Apps Script, I'm trying to move some transaction data from one sheet and organize it on a different sheet with subtotal rows for each customer account (called "Units") with a grand total at the bottom.
I have the transactions organized in an array of objects as key:value pairs ("transactions", the keys are headers, some values are strings, others are numbers), and I have the units in a 2nd array called "unitList". I want to iterate through each element in the unitList array, and pull each transaction with a matching unit onto my "targetSheet", then append a subtotal row for each unit.
----- UPDATE 10/7/2018 3:49PM EST -----
Thanks to everyone for your input - I took your advice and ditched the library I was using and instead found better getRowsData and appendRowsData functions which I put directly in my code project. This fixed the array filter problem (verified by logging filterResults), BUT, now when I call appendRowsData(), I get this error:
The coordinates or dimensions of the range are invalid. (line 73, file "Display Transactions")
Line 73 is the line below, in the appendRowsData function. Any help on how to fix this would be greatly appreciated.
var destinationRange = sheet.getRange(firstDataRowIndex, 1, objects.length, 9);
Here's my project in it's entirety thus far:
function displayTransactions() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Label each sheet
var dashboard = ss.getSheetByName('Dashboard');
var unitsSheet = ss.getSheetByName('Unit Ref Table');
var transactionsSheet = ss.getSheetByName('Transactions Ref Sheet');
var targetSheet = ss.getSheetByName('Target Sheet');
// Returns true if the cell where cellData was read from is empty.
// Arguments:
// - cellData: string
function isCellEmpty(cellData) {
return typeof(cellData) == "string" && cellData == "";
}
// Define function that converts arrays into JSON
// For every row of data in data, generates an object that contains the data.
// Names of object fields are defined in keys.
// Arguments:
// - data: JavaScript 2d array
// - keys: Array of Strings that define the property names for the objects to create
function getObjects(data, keys) {
var objects = [];
for (var i = 0; i < data.length; ++i) {
var object = {};
var hasData = false;
for (var j = 0; j < data[i].length; ++j) {
var cellData = data[i][j];
if (isCellEmpty(cellData)) {
continue;
}
object[keys[j]] = cellData;
hasData = true;
}
if (hasData) {
objects.push(object);
}
}
return objects;
}
// Define function that pulls spreadsheet data into arrays, then converts to JSON using getObjects function
function getRowsData(sheet) {
var headersRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
var headers = headersRange.getValues()[0];
var dataRange = sheet.getRange(sheet.getFrozenRows()+1, 1, sheet.getLastRow(), sheet.getLastColumn());
return getObjects(dataRange.getValues(), headers);
}
// Define function appendRowsData that uses getLastRow to fill in one row of data per object defined in the objects array.
// For every Column, it checks if data objects define a value for it.
// Arguments:
// - sheet: the sheet object where the data will be written
// - objects: an array of objects, each of which contains data for a row
function appendRowsData(sheet, objects) {
var headersRange = sheet.getRange(7, 1, 1, 9);
var firstDataRowIndex = sheet.getLastRow() + 1;
var headers = headersRange.getValues()[0];
var data = [];
for (var i = 0; i < objects.length; ++i) {
var values = []
for (j = 0; j < headers.length; ++j) {
var header = headers[j];
values.push(header.length > 0 && objects[i][header] ? objects[i][header] : "");
}
data.push(values);
}
var destinationRange = sheet.getRange(firstDataRowIndex, 1, objects.length, 9);
destinationRange.setValues(data);
}
// Call getRowsData on transactions sheet
var transactions = getRowsData(transactionsSheet);
// Get array of units
var unitList = unitsSheet.getRange("B2:B").getValues();
// Iterate through the unitList and pull all transactions with matching unit into the target sheet
for (var i=0; i < unitList.length; i++) {
var subTotal = 0;
var grandTotal = 0;
var filterResults = transactions.filter(function(x) {
return x['Unit'] == unitList[i];
})
Logger.log(filterResults); // This brings the correct results!
// Display matching transactions
appendRowsData(targetSheet, filterResults);
// Grand total at the bottom when i=units.length
}
}
I'm trying to fetch my ETH balance and transactions from etherscan.io website and I'm trying to use the same code I used before for another website. But it seems returning me an empty array, and also the error "The coordinates or dimensions of the range are invalid."
This is the code:
function getTx() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var url = 'http://api.etherscan.io/api?module=account&action=txlist&address=0x49E81AA0cFE7eeA9738430212DC6677acF2f01a1&sort=asc';
var json = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(json);
var rows = [],
array;
for (i = 0; i < data.length; i++) {
array = data[i];
rows.push([array.timeStamp, array.from, array.to, array.value]);
}
Logger.log(rows)
askRange = sheet.getRange(3, 1, rows.length, 3);
askRange.setValues(rows);
}
The logged "rows" is empty, what am I doing wrong?
Thank you
How about a following modification?
Modification points :
There is data you want at data.result.
Number of columns of data is 4.
Modified script :
function getTx() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var url = 'http://api.etherscan.io/api?module=account&action=txlist&address=0x49E81AA0cFE7eeA9738430212DC6677acF2f01a1&sort=asc';
var json = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(json);
var rows = [],
array;
for (i = 0; i < data.result.length; i++) { // Modified
array = data.result[i];
rows.push([array.timeStamp, array.from, array.to, array.value]);
}
Logger.log(rows)
askRange = sheet.getRange(3, 1, rows.length, 4); // Modified
askRange.setValues(rows);
}
If I misunderstand your question, I'm sorry.
(I am working with Angular but this is not an angular specific problem).I have a json object that i am trying to disect. I've been trying to get my head around this and have come up with a complicated script with nested for loops that isn't working. The object consists of 3 arrays. The first array is an array of fieldnames. The third array is an array of arrays that correspond to the field names like so:
object = {"fields" : [array], "type" : [array], "values" : [array]}
where:
fields = ["user","bananas","pies","apples","pears","mangos","date"]
values = [["Bongo","12","2","1","2","4","05-02-2015"], ["Mongo","12","23","15","22","43","05-02-2015"], ["Congo","15","32","21","23","44","06-02-2015"]]
What i want to do is count the amount of fruit that all users had on a specific date. for instance i want to know how many bananas all users had on "06-02-2015".
I can post my code, but i think that would only work confusing as it's probably wrong and redundant.
update:
I've tried the filter but can't get it to work because the values inside object.values don't have a name. So i think it should be something like this:
var fruits = $filter('filter')(object.value, {???[6] : "2015-04-29 00:00:00"}, true);
I'm not sure what the ??? should be.
solved:
simply removing the name did the trick.
var fruits = $filter('filter')(object.value, "2015-04-29 00:00:00", true);
This script should group the values by date:
var fields = ["user","bananas","pies","apples","pears","mangos","date"];
var values = [["Bongo","12","2","1","2","4","05-02-2015"], ["Mongo","12","23","15","22","43","05-02-2015"], ["Congo","15","32","21","23","44","06-02-2015"]];
var result = {};
for (var j = 0; j < values.length; j++) {
if (!result.hasOwnProperty(values[j][fields.length - 1]))
result[values[j][fields.length - 1]] = {};
for (var i = 1; i < fields.length - 1; i++) {
if (!result[values[j][fields.length - 1]][fields[i]])
result[values[j][fields.length - 1]][fields[i]] = parseInt(values[j][i], 10);
else
result[values[j][fields.length - 1]][fields[i]] += parseInt(values[j][i], 10);
}
}
console.log(result);
What you need is a filter:
var fruits = $filter('filter')(object, {date: $choosenDate}, true);
Then, if you want to split fruit by type, you can use angular.forEach to iterate on the nev fruits var
This would be a lot simpler if the structure of the arrays wasn't bananas, so to speak.
var fields = ["user","bananas","pies","apples","pears","mangos","date"];
var values = [["Bongo","12","2","1","2","4","05-02-2015"], ["Mongo","12","23","15","22","43","05-02-2015"], ["Congo","15","32","21","23","44","06-02-2015"]];
var date, dataArray, dateIndex = (fields.length - 1),
dates = {};
for (var i = 0; i < values.length; i++) {
dataArray = values[i];
date = dataArray[dateIndex];
dates[date] = dates[date] || {};
for (j = 1; j < fields.length - 1; j++) {
dates[date][fields[j]] = dates[date][fields[j]] || 0;
dates[date][fields[j]] += Number(dataArray[j]);
}
}
console.log(dates);
How can I splice an array within another array?
I'm trying to create a game for kids in my class. Some kind of a trivia history question creator. How to splice the MasterArray so that I would get rid of sub-arrays (Hard-England and Medium-England) within the allEnglandArray. Because the "MasterArray.splice()" seem to be affecting - splicing only the allEngland array, or the allFrance array. But I need to get rid of those sub-arrays...
My code:
var Easy-England:Array = ["item1","item2","item3","item4","item5"];
var Medium-England:Array = ["item6","item7","item8"];
var Hard-England:Array = ["item9","item10"];
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
var Easy-France:Array = ["item11","item12","item13","item14","item15"];
var Medium-France:Array = ["item16","item17","item18"];
var Hard-France:Array = ["item19","item20"];
var allFrance:Array = [Easy-France,Medium-France,Hard-France];
// the list of countries goes on and on and on... (Italy, Hungary, etc.)
var allStuff:Array = [allEngland, allFrance, etc.];
var MasterArray:Array;
// FUNCTIONS
// clear MasterArray - first I clear out completely the MasterArray
function clearMasterArray():void
{
MasterArray.splice(0);
}
// update MasterArray - than I fill the MasterArray with data according to checkBoxes
function updateMasterArray():void
{
for (var i:int = 0; i<checkBoxBlock.myCheckBoxes.length; i++)
{
if (checkBoxBlock.myCheckBoxes[i].selected)
{
MasterArray.push(allStuff[i]);
}
}
}
// splice MasterArray - last thing I do is splice the items according to student's proficiency level, referred to as "studentPL".
function spliceMasterArray():void
{
if (studentPL == 1)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(5,5);
}
}
if (studentPL == 2)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(8,2);
}
}
if (studentPL == 3)
{
for (var i:int = 0; i<allStuff.length; i++)
{
trace("no need to splice");
}
}
}
And after this I call those functions in another function in this order...
function creatorFunction():void
{
clearMasterArray();
updateMasterArray();
spliceMasterArray();
}
Instead of:
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
try this:
var allEngland:Array = Easy-England.concat(Medium-England, Hard-England);
This way you will have a 'flat' array (no sub-arrays), so it will be easier to deal with.