I am having JSON object
var jsonData={
"key1":val1,
"key2":val2
}
I am having array
var columns=[100,101,102,103];
var resultarray=[{C_100:1,C_101:2,102:3,C_103:4},{C_100:5,C_101:6,C_102:7,C_103:8};
I am looping through result array to get create json object matching the values of columns
for(let i=0;i<resultarray.length; i++)
{
var finalRes=resultarray[i];
for (let column = 0; column < columns.length; column++) {
dataVal = finalRes["C_"+columns[column]];
jsonData[columns[column]] = dataVal;
}
}
I want to add json key value pairs in the lopp to existing json object already created.
I am getting jsonObject output as
var jsonData=
{
100:1,
101:2,
102:3,
key1:val1,
key2:val2,
}
Which will not work for my scenario
I am expecting json object as
var jsonData=
{
key1:val1,
key2:val2,
100:1,
101:2,
102:3,
}
Please let me know how to push items to existing json object which should append at the end;
I tried this way and it worked.
I have appended c_ for each column and evrything is string it got appeneded correctly in order.
var columns=[C_100,C_101,C_102,C_103];
for(let i=0;i<resultarray.length; i++)
{
var finalRes=resultarray[i];
for (let column = 0; column < columns.length; column++) {
dataVal = finalRes[columns[column]];
jsonData[""+columns[column]""] = dataVal;
}
}
Now i got out put of JsonData as
var jsonData=
{
key1:val1,
key2:val2,
C_100:1,
C_101:2,
C_102:3,
C_103:4
}
No i have to work around to remove "C_" from key
Related
So I have a script (google apps script) that pulls data from one of my sheets (to pairs: initials && percentage) that has changing values (sometimes it's only weekly other times it's daily).
It's supposed to check the old values against the new values and only process the new values, but it's processing for all values for some reason.
During the loop process it starts by finding the email attached to that cell and then sends a generated email to the person. Then at the end it stores the new values found over the previous.
Getting New Data & Variables
var data = dataRange.getValues(); // Fetch values for each row in the Range.
var oldData = [{}];
//Declare variable
Getting Old Data from document properties.
var oldValues = PropertiesService.getDocumentProperties().getProperties();
//get values from document properties
var outerArrayOldData = [];
//empty array
var arr4 = [];
//empty array
var thisLoopString,
thisRowArray;
for (var key in oldValues) {
//grabbing keys from document properties 'row[i]' and loop for each
thisLoopString = oldValues[key];
thisRowArray = []; //Reset
array
thisRowArray = thisLoopString.split(","); //Convert the string to partial array
arr4.push(thisRowArray); //Push the inner array into the outer array
outerArrayOldData = arr4.concat(outerArrayOldData); //convert outer to actual usable array
var arr4 = []; //reset arr4 back to 0
};
//End getting old data
Comparing old data to new data
var oldData = outerArrayOldData;
var source = oldData.map(function (row) {
return JSON.stringify(row);
//map array to string
}),
searchRow,
dataLength = data.length;
for (i = 0; i < dataLength; i += 1) {
searchRow = JSON.stringify(data[i]);
if (source.indexOf(searchRow) == -1) {
//search old data and compare to new data using index search and if data isn't in old stack process it through functions
//doing stuff with new pairs
}
}
}
}
How old data is stored to Doc properties.
var objOldData = {};
//empty
var keyName = "",
//empty
thisRowArray;
for (i = 0; i < data.length; i++) {
keyName = "row" + (i).toString();
//set keys
thisRowArray = data[i].toString();
//convert each pair array to string
if (thisRowArray == "") continue;
//skip blanks
objOldData[keyName] = thisRowArray;
//add keys and values to properties as a string
}
PropertiesService.getDocumentProperties().setProperties(objOldData,
true); //true deletes all other properties
//Store the Updated/New Values back to Properties
}
Logger Console:
<<<<<<<<Imported Range data>>>>>>>>
[[BBB, 0.9], [CCC, 0.76], [DDD, 0.89], [, ]]
<<<<<<<<Old data from dpcument properties>>>>>>>>
[[DDD, 0.89], [, ], [BBB, 0.9], [CCC, 0.76]]
<<<<<Processing New Values Not in Old Data>>>>>
[CCC, 0.76]
[BBB, 0.9]
[DDD, 0.89]
<<<<<<<<Store the Updated/New Values back to Properties>>>>>>>>
{row1=CCC,0.76, row0=BBB,0.9, row3=,, row2=DDD,0.89}
As you can see it's still processing all the values even though they are not new and already exist in the system. How come the search isn't finding that they already exist? WHere did I go wrong on this?
In your "Comparing old data to new data" for loop code, try changing:
searchRow = JSON.stringify(data[i]);
to:
searchRow = JSON.stringify([data[i][0], data[i][1].toString()]);
This ensures that the value at the second array index is always converted into a string for comparison to the "old" imported value, which appears to be parsed from a row delivered as a string.
It looks like, currently, new data array values declared with the second value as numeric, (or perhaps null or empty value):
[["BBB", 0.9], ["CCC", 0.76], ["DDD", 0.89], ["",""]];
While "old" rows (imported from Google doc) are imported and converted into an array, where the values are strings:
[["CCC","0.76"],["BBB","0.9"],["",""],["DDD","0.89"]]
On comparing rows with JSON.stringify, for example, '["DDD","0.89"]' does not match '["DDD",0.89]', so all rows are getting erroneously registered as "new".
I did a bit of guessing from your example to arrive at this, but it could be the cause of your bug. Good luck!
I have trouble understanding your code, so I created my own instead:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var data = {};
function getData() {
var range = sheet.getRange("A1:B3");
var values = range.getValues();
for (var i=0; i < values.length; i++) {
var key = 'row' + i;
var currentRow = values[i];
// for each cell value,
// toString : convert to string
// trim : remove all whitespaces from both ends of cell values
// encodeā¦ : encode the values so we don't have any ","
var arr = currentRow.map(function(v){return encodeURIComponent(v.toString().trim())});
// join the array with "," delimiter
var s = arr.join();
data[key] = s;
}
} // getData()
function saveData() {
getData();
PropertiesService.getDocumentProperties().setProperties(data);
}
function compareData() {
getData();
var props = PropertiesService.getDocumentProperties().getProperties();
for (var idx in props) {
if (idx in data) {
if (data[idx] != props[idx]) {
Logger.log('\n%s is different\nOld value is "%s"\nNew value is "%s"',
idx,
decodeURIComponent(props[idx]),
decodeURIComponent(data[idx]));
}
} else {
Logger.log('missing row: ' + idx);
}
}
}
// Test function. Check all document properties
function peekProperties() {
var props = PropertiesService.getDocumentProperties().getProperties();
for (var idx in props) {
Logger.log('%s = %s', idx, props[idx]);
}
}
Question: what if a row is deleted? Shouldn't key be the value in A column instead of row number?
Turns out that my localStorage["items"] stored my JSON as a string.
"["{\"itemId\":1, \"itemName\":\"item1\"}", "{\"itemId\":2, \"itemName\":\"item2\"}",
"{\"\":3, \"itemName\":\"item3\"}",]"
This is what it looks like when I JSON.parse(localStorage["items"]):
["{"itemId":1, "itemName":"item1"}", "{"itemId":2, "itemName":"item2"}"
"{"itemId":3, "itemName":"item3"}"]
So in my loop I made it into an object by using jQuery.parseJSON:
var object = jQuery.parseJSON(item[i]);
Right now, what I want to do is delete the object where itemId = 3 and make sure that the object is totally removed from the localStorage.
Here's my Javascript so far:
$("#button_delete").on("click", function(e){
e.preventDefault();
var items = JSON.parse(localStorage.getItem('items'));
for (var i = 0; i < items.length; i++) {
var object = JSON.parse(items[i]);
if(object.request_id == 3){
console.log(items)
delete items[i] // slice doesn't work not sure why
console.log(items)
}
}
item = JSON.stringify(items);
console.log(item);
localStorage.setItem('items', item);
})
UPDATED
When I click the button now, it will delete that item however it will not delete the comma before it.
When I check the localStorage["items"] in the browser it returns this:
"["{\"itemId\":1, \"itemName\":\"item1\"}","{\"itemId\":2, \"itemName\":\"item2\"}",null]"
I have another page that will display the info in the html and it returns the error:
Uncaught TypeError: Cannot read property 'itemId' of null.
So right now is there a way to check or search in localStorage["items"] specifically for ,null and remove it so that the error won't show?
Code on how I'm displaying the info in HTML:
var items = JSON.parse(localStorage.getItem('items'));
var itemsHTML = "";
for(var i = 0; i < items.length; i++){
var object = jQuery.parseJSON(items[i]);
var displayItemId = object.itemId;
var displayItemName = object.itemName;
itemsHTML += "<li id="+displayItemId+">"+displayItemName+"</li>";
}
$("#viewItemList").html(itemsHTML);
All the answers were right but you have to :
Parse the string in localStorage to JSON (you did that)
Remove the item you don't want (with slice() )
Make the JSON to string
Re-set it in the localStorage
So :
1.
var items = JSON.parse(localStorage.getItem("items")); // updated
2.
for (var i =0; i< items.length; i++) {
var items = JSON.parse(items[i]);
if (items.itemId == 3) {
items.splice(i, 1);
}
}
3.
items = JSON.stringify(items); //Restoring object left into items again
4.
localStorage.setItem("items", items);
Parsing to JSON and storing it as string is kinda annoying, but that's the way localStorage works.
Try this one.
$("#button_delete").on("click", function(e){
e.preventDefault();
var items = JSON.parse(localStorage["items"]);
for (var i = 0; i < items.length; i++) {
if(items[i].itemId == 3){
items.splice(i,1);
break;
}
}
})
If you know the key of the specific item - do it short and simple like this:
if (localStorage.getItem('key_to_remove') != null)
localStorage.removeItem('key_to_remove');
localstorage can contain strings only
So first you have to parse items from localstorage (like u do now)
Remove from it the element you don't want.
Serialize it to JSON one more time and store in localstorage.
Here is the approach
var items = localStorage["items"];
for (var i =0; i< items.length; i++) {
var item = JSON.parse(items[i]);
if (item.itemId == 3) {
items.slice(i);
break;
}
}
// Don't forget to store the result back in localStorage
localStorage.setItem("items", items);
eliminar(est: string) {
//estudiantes ES LA KEY
var items = JSON.parse(localStorage.getItem('estudiantes'));
for (var i = 0; i < items.length; i++) {
var item = items[i];
if(item.id == est){
items.splice(i,1);
}
}
items = JSON.stringify(items);
localStorage.setItem('estudiantes', items);
this.getAll();
}
I'm trying to save certain JSON values to JS array.
var count = Object.keys(item.programme).length; // item is JSON file, count is 23
for (i=0; i<count; i++) {
var title = item.programme[i].title.de;
console.log(typeof title); //string
console.log(title); // desired values, title when i
listData = [];
listData[i] = title;
}
console.log(listData); // [undefined, undefined,.....,title when i =22]
I would like to get array of values from title variable. I get desired value only in last field of array, rest is undefined.
It is kind of trivial. You define listData in each iteration. Move it outside the loop:
var listData = [];
for (var i=0; i<count; i++) {
...
listData[i] = title;
}
I have a array as:
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"] // dynamic
Json data comming from backend as:
info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84}
suppose I want to select market cap then I can do info.marketCap. But I want to select only those json values which keys are equals to cols i.e. info.ticker, info.highPrice, info.lowPrice
and assign N/A to those which is undefined in json but present in cols array i.e info.lastPrice = "N/A"
Note: cols changes from time to time
Here is what I have got so far
SyScreener.fillScreenerResult = function(info) {
var cols = ["ticker", "highPrice", "lowPrice", "openPrice", "lastPrice", "currentVol", "avgVol"];
var data = [];
for(var i=0; i<info.length; i++) {
var jsonKeys = Object.keys(info[i]);
for(var j=0; j<jsonKeys.length; i++) {
if(cols.contains(jsonKey[j])) {
// TODO something like - data.push([info[i].jsonKey[j])
} else {
// TODO something like - info[i].colsValue = "N/A"
}
}
}
SyUtils.createDataTable("screener_result", data);
};
do you mean something like this:
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"];
info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84};
for(var c = 0, clen = cols.length; c < clen; c++) {
if( !(cols[c] in info) ) {
console.log("N/A");
}
else {
console.log(info[cols[c]]);
}
}
Demo:: jsFiddle
I may not be reading your question correctly but from my understanding I might suggest something like this.
for (var i=0; i<cols.length; i++) {
var fieldName = cols[i];
if (!info.hasOwnProperty(fieldName)) {
info[fieldName] = 'N/A';
}
}
This simply iterates through each field name in cols and checks if it is a property of the info JSON object. If it isn't already present the loop adds the property with a value of 'N/A'.
var cols = ["ticker", "highPrice", "lowPrice","lastPrice"]
var info = {ticker: "AAPL", marketCap: 2800000000, lowPrice: 42.72, highPrice: 42.84}
var output = {};
for(each in info) {
var index = cols.indexOf(each)
if(index != -1) {
output[each] = info[each];
//remove extra already checked element
cols.splice(index,1)
}
}
//append remaining keys
for(var i=0;i<cols.length;i++) {
output[cols[i]] = "N/A"
}
console.log(output)
//output Object {ticker: "AAPL", lowPrice: 42.72, highPrice: 42.84, lastPrice: "N/A"}
First thing, you nedd deserialize you JSON data.
To do this using jQuery use the function parseJson that you can find here
http://api.jquery.com/jquery.parsejson/
once you deserialized it, you can do whatever you want with this data since you manipulate it as a plain javascript array. Hope this helps.
I have a question about manipulating JSON data using Javascript and stringify/parse. In the below example, I create a JSON string, then use parse to convert it back into an object. After doing that, what I want to do is delete an item with a certain ID, and the only way I can find to do it is to loop through the entire array and delete the element from the array once I find a match. This doesn't seem very efficient. Is there a better way to do this?
var employees = [];
//build the array
for (var i=0; i < 10; i++) {
var player = { "id": i, "salary": i*1000000 };
employees.push(player);
}
json_employees = JSON.stringify({employees: employees}); //convert to json string
alert(json_employees); //display the new string
var obj = JSON.parse(json_employees); //convert back to a Javascript object
for (var j=0; j < obj.employees.length; j++) { // loop through the array
if (obj.employees[j].id === 5) // is it the employee with id 5?
obj.employees.splice(j, 1); // remove the fifth item
}
json_modified_employees = JSON.stringify({employees: obj.employees}); //convert back to json string
alert(json_modified_employees); //display the new string
You could store the employees in an object, with a key of their id, something like this:
// create a store object
var employees = {};
//build the array
for (var i=0; i < 10; i++) {
var player = { "id": i, "salary": i*1000000 };
// add item to store object with a key of 'pk' + i
employees['pk' + i] = player;
}
json_employees = JSON.stringify({employees: employees}); //convert to json string
alert(json_employees); //display the new string
var obj = JSON.parse(json_employees); //convert back to a Javascript object
// remove the required item (in this case number 5)
delete obj.employees['pk' + 5];
json_modified_employees = JSON.stringify({employees: obj.employees}); //convert back to json string
alert(json_modified_employees); //display the new string
If you then wanted to iterate over your employees, you would
for (var key in employees) {
if (employees.hasOwnProperty(key)) {
alert(employees[key].id)
}
}