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;
}
Related
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
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?
I m new a web developer and i face up the following problem:
"Cannot read property 'length' of undefined"
my code:
var data=();
for(var i;i<parseInt(window.localStorage["numOfInserts"]);i++){
data["category_name"]=localStorage.getItem(("category_name_"+i).toString());
data["category_id"]=localStorage.getItem(("category_id_"+i).toString());
data["provider_name"]=localStorage.getItem(("provider_name_"+i).toString());
data["provider_id"]=localStorage.getItem(("provider_id_"+i).toString());
data["appointment_date"]=localStorage.getItem(("appointment_date_"+i).toString());
data["appointment_time"]=localStorage.getItem(("appointment_time_"+i).toString());
}
$scope.allAppointments=dataArray;
for(var i=0;i<dataArray.length;i++){
$scope.showme[i]=false;
}
After some research I understand that the problem caused to the fact that data is an array but I try to turn it to json, but
var data ={};
gives me the same error as before.
Please Help me
I think this is what you're looking for, see code comments:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array, using the information
// from local storage. Note that you don't need toString() here.
// Once we've created the object (the {...} bit), we push it onto
// the array
data.push({
category_name: localStorage.getItem("category_name_"+i),
category_id: localStorage.getItem("category_id_"+i),
provider_name: localStorage.getItem("provider_name_"+i),
provider_id: localStorage.getItem("provider_id_"+i),
appointment_date: localStorage.getItem("appointment_date_"+i),
appointment_time: localStorage.getItem("appointment_time_"+i)
});
}
This does the same thing, it's just more verbose and so could help you understand more clearly what's going on:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array
var obj = {};
// Fill it in from local storage. Note that you don't need toString() here.
obj.category_name = localStorage.getItem("category_name_"+i);
obj.category_id = localStorage.getItem("category_id_"+i);
obj.provider_name = localStorage.getItem("provider_name_"+i);
obj.provider_id = localStorage.getItem("provider_id_"+i);
obj.appointment_date = localStorage.getItem("appointment_date_"+i);
obj.appointment_time = localStorage.getItem("appointment_time_"+i);
// Push the object onto the array
data.push(obj);
}
You need to create an array(dataArray before the loop), and create a new object in each iteration and set the property values for that object then add the object to the array like below
var dataArray = [],
data, numOfInserts = parseInt(window.localStorage["numOfInserts"]);
for (var i = 0; i < numOfInserts; i++) {
data = {};
data["category_name"] = localStorage.getItem(("category_name_" + i).toString());
data["category_id"] = localStorage.getItem(("category_id_" + i).toString());
data["provider_name"] = localStorage.getItem(("provider_name_" + i).toString());
data["provider_id"] = localStorage.getItem(("provider_id_" + i).toString());
data["appointment_date"] = localStorage.getItem(("appointment_date_" + i).toString());
data["appointment_time"] = localStorage.getItem(("appointment_time_" + i).toString());
dataArray.push(data)
}
$scope.allAppointments = dataArray;
for (var i = 0; i < dataArray.length; i++) {
$scope.showme[i] = false;
}
It looks like you're trying to create an associative array, so the first line should indeed be
var data = {};
The next part is fine, but then it looks like you want to enumerate the keys
for(var i=0;i<Object.keys(data).length;i++){
$scope.showme[i]=false;
}
Help needed.
I have string like ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"] (unlimited number of pairs)
I need to make an array with pair like wT (as index) and WLw as value, for the whole string (or simpler wT as index0, WLw as index 1 and so on)
I'm trying to do it in JavaScript but I just cant figure out how to accomplish this task.
Much much appreciate your help!!
You cannot have a string as an index in an array, what you want is an object.
All you need to do is loop over your array, split each value into 2 items (key and value) then add them to an object.
Example:
// output is an object
var output = {};
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
If you wanted an array of arrays, then its much the same process, just pushing each pair to the output object
// output is a multidimensional array
var output = [];
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
output.push(source[index].split("="));
}
Update If your source is actually a string and not an array then you will have to do a little more splitting to get it to work
var output = {};
var sourceText = "[\"wt=WLw\",\"V5=9jCs\",\"7W=71X\",\"rZ=HRP9\"]";
// i have escaped the quotes in the above line purely to make my example work!
var source = sourceText.replace(/[\[\]]/g,"").split(",");
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
Update 2
If your desired output is an array of arrays instead of an object containing key-value pairs then you will need to do something like #limelights answer.
Object with Key-Value pairs: var myObject = { "key1": "value1", "key2": "value2" };
with the above code you can access "value1" like this myObject["key1"] or myObject.key1
Array of Arrays: var myArray = [ [ "key1", "value1"] ,[ "key2", "value2" ] ];
with this code, you cannot access the data by "key" (without looping through the whole lot to find it first). in this form both "key1" and "value1" are actually values.
to get "value1" you would do myArray[0][1] or you could use an intermediary array to access the pair:
var pair = myArray[0];
> pair == ["key1", "value1"]
> pair[0] == "key1"
> pair[1] == "value1"
You can use a for each loop on both types of result
// array of arrays
var data = [ [ "hello", "world"], ["goodbye", "world"]];
data.forEach(function(item) {
console.log(item[0]+" "+item[1]);
});
> Hello World
> Goodbye World
// object (this one might not work very well though)
var data = { "hello": "world", "goodbye": "world" };
Object.keys(data).forEach(function(key) {
console.log(key+" "+data[key]);
});
> Hello World
> Goodbye World
The normal for loop would do perfectly here!
var list = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
var pairs = [];
for(var i = 0; i < list.length; i++){
pairs.push(list[i].split('='));
}
This would give you an array of pairs, which I assume you want.
Otherwise just get rid of the outer Array and do list[i].split('=');
If you want it put into an object ie. not an Array
var pairObject = {};
for(var i = 0; i < list.length; i++){
var pair = list[i].split('=');
pairObject[pair[0]] = pair[1];
}
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)
}
}