My loop function is as below
var resources= jsonObj.entry;
var resourceType;
var i;
for (i = 0; i < resources.length; i++) {
resourceType += resources[i];
}
console.log(resourceType)
if i do jsonObj.entry[0] i get the first entry so i implemented for-loop to get all the entries but console.log on resourceType prints the following
So, one way to do it is
var resources = jsonObj.entry;
var resourceTypeArray = [];
var resourceType = "";
for (let item = 0; item <= resources.length; item++) {
// This will remove all cases where the item doesn't exist and/or resource doesn't exist
if(resources[item] && resources[item].resource){
resourceTypeArray.push(resources[item].resource);
resourceType += JSON.stringify(resources[item].resource);
}
}
// printing out to the console the array with resources
console.info(resourceTypeArray);
// printing out to the console the string with the concatenation of the resources
console.info(resourceType);
I also created a StackBlitz with the working solution and your json file kindly provided.
hope it helps.
Related
What I am trying to do is:
set an array value (list) to another array (options).
If the user's input (searchVal) matches with a list value it will delete options, push this match, and then will keep pushing the next matches without deleting options again.
So according to the code below, if searchVal was "whatever", options should return: ["whatever", "whatevEver1"] but, instead, it returns: ["whatever", "WhatEver1", "whatttever", "whatever", "whatevEver1"]
Relevant code:
var list = ["whatever", "WhatEver1", "whatttever"];
var clear = 0;
var options = [];
for (var i=0 ; i < list.length ; i++)
{
options.push([list[i]]);
}
var searchVal = window.prompt(" ");
for (var i=0 ; i < list.length ; i++)
{
if (list[i].toLowerCase().includes(searchVal.toLowerCase())) {
if (clear == 0) {
options.length = 0;
}
options.push([list[i]]);
}
clear++;
}
return options;
Js arrays are pass-by-reference. In order to make independent copy of array you need to use:
let options = JSON.parse(JSON.stringify(list));
I didnt try to implement this to your problem cause im too lazy but i think it might work.
I am using a Google Apps Script that pulls the content from a feed in a sheet.
This is the code that I'm using:
function processXML(FeedURL,sheetsFileDestinationURL,rawPasteSheetName,OPT_childNamesArray,OPT_Namespace){
var OPT_childNamesArray = ["link"]; // get only item url from the feed
var GoogleSheetsFile = SpreadsheetApp.openByUrl(sheetsFileDestinationURL);
var GoogleSheetsPastePage = GoogleSheetsFile.getSheetByName(rawPasteSheetName);
if (OPT_childNamesArray){
GoogleSheetsPastePage.getDataRange().offset(1,0).clearContent(); // get all filled cells, omitting the header row, and clear content
}
else {
GoogleSheetsPastePage.getDataRange().offset(0,0).clearContent(); // get all filled cells, INCLUDING the header row, and clear content
}
// Generate 2d/md array / rows export based on requested columns and feed
var exportRows = []; // hold all the rows that are generated to be pasted into the sheet
var XMLFeedURL = FeedURL;
var feedContent = UrlFetchApp.fetch(XMLFeedURL).getContentText(); // get the full feed content
var feedItems = XmlService.parse(feedContent).getRootElement().getChild('channel').getChildren('item'); // get all items in the feed
for (var x=0; x<feedItems.length; x++){
// Iterate through items in the XML/RSS feed
var currentFeedItem = feedItems[x];
var singleItemArray = []; // use to hold all the values for this single item/row
// Parse for specific children (requires names and namespace)
if (OPT_childNamesArray){
for (var y=0; y<OPT_childNamesArray.length; y++){
// Iterate through requested children by name and fill rows
var currentChildName = OPT_childNamesArray[y];
if (OPT_Namespace){
if (currentFeedItem.getChild(OPT_childNamesArray[y],OPT_Namespace)){
singleItemArray.push(currentFeedItem.getChildText(OPT_childNamesArray[y],OPT_Namespace));
}
else {
singleItemArray.push("null");
}
}
else {
if (currentFeedItem.getChild(OPT_childNamesArray[y])){
singleItemArray.push(currentFeedItem.getChildText(OPT_childNamesArray[y]));
}
else {
singleItemArray.push("null");
}
}
}
exportRows.push(singleItemArray);
}
// Parse for ALL children, does not require knowing names or namespace
else if (!OPT_childNamesArray){
var allChildren = currentFeedItem.getChildren();
if (x == 0){
// if looking at first item, create a header row first with column headings
var headerRow = [];
for (var h=0; h<allChildren.length; h++){
headerRow.push(allChildren[h].getName());
}
exportRows.push(headerRow);
}
for (var c=0; c<allChildren.length; c++){
singleItemArray.push(allChildren[c].getText());
}
exportRows.push(singleItemArray);
}
}
// Paste the generated md array export into the spreadsheet
if (OPT_childNamesArray){
GoogleSheetsPastePage.getRange(2,1,exportRows.length,exportRows[1].length).setValues(exportRows);
}
else if (!OPT_childNamesArray){
var maxRangeLength = 0;
var currentRowIndex = 1;
for (var x = 0; x<exportRows.length; x++){
if (exportRows[x].length > maxRangeLength){
maxRangeLength = exportRows[x].length;
}
GoogleSheetsPastePage.getRange(currentRowIndex,1,1,exportRows[x].length).setValues([exportRows[x]]);
currentRowIndex++;
}
}
}
My problem is this:
When I run this code I get:
https://url/115-396/
https://url/115-396/
https://url/115-396/
I need to remove "115-396/".
So I tryed to add this code but didn't work:
...
// Paste the generated md array export into the spreadsheet
if (OPT_childNamesArray){
for (var k = 0; k < exportRows.length; k++) {
var re = '115-396/'
var replacingItem = '';
var URL = exportRows[0].toString().replace(re, replacingItem);
}
GoogleSheetsPastePage.getRange(2,1,exportRows.length,exportRows[1].length).setValue(URL);
}
else if (!OPT_childNamesArray){
...
Edit after #Yuri reply:
// Paste the generated md array export into the spreadsheet
if (OPT_childNamesArray){
for ( k=0; k < exportRows[0].length; k++) {
var re = '115-396/'
var replacingItem = '';
exportRows[0][k] = exportRows[0][k].toString().replace(re, replacingItem);
}
GoogleSheetsPastePage.getRange(2,1,exportRows.length,exportRows[1].length).setValues(exportRows);
}
result:
https://url/
https://url/115-396/
https://url/115-396/
Basically, the regex is applied only to the first url.
How I can make that the regex is applied to all the url's?
Any help?
Thanks
You are using a for to iterate thru the exportRow array, but later on, you're not using the k iterator inside the for.
Then, you are not accessing the exportRows array, only the first position:
var URL = exportRows[0].toString().replace(re, replacingItem);
Shouldn't be?
var URL = exportRows[k].toString().replace(re, replacingItem);
In that case, it won't work, because URL it's not an array, so by doing this you are only saving the last assignation produced on the for iterator on the URL, I believe you are trying to do the following:
for ( k=0; k < exportRows.length; k++) {
var re = '115-396/'
var replacingItem = '';
exportRows[k] = exportRows[k].toString().replace(re, replacingItem);
}
And you'll have exportRows as an array of the desired url's without the 115-396 extensions.
Now you can place this on the spreadsheet with setValue as you were doing, but setValue is for strings, integers, etc, and not for arrays. For arrays you have setValues()
GoogleSheetsPastePage.getRange(2,1,exportRows.length,exportRows[1].length).setValues(exportRows);
But, then, the range of exportRows should match the range of your getRange selection, which I'm not sure it's happening.
Just to clarify it, exportRows.length is the length of the array, and exportRows[1] is the length of the string/url stored on the position 1 of the array.
Hope this helps, the question is not really clear neither the intentions, provide more info if still not working.
How to know the size of the range you're getting?
var myrange = GoogleSheetsPastePage.getRange(2,1,exportRows.length,exportRows[1].length)
Logger.log(myrange.getNumRows());
Logger.log(myrange.getNumColumns());
You'll be able to know the range you have on getRange and make it match with the exportRows size.
Make sure to check the attached documentation, and in case you have more doubts please open a new question related to it.
I am using p5 loadJSON to import data, the data gives an array with so many records and sub-arrays.
For example, data.records[i].form_values["94d5"] gives me a name.
I am currently using a for loop to go through data.records.length and give me an array of some key pieces of data relative to each record I want to see.
Problem:
I want to loop through the records and get the value of:
data.records[i].form_values["94d5"].choice_values["0"], but some records don't have form_values["94d5"], for example. I just want to skip empty sections (leave undefined like empty items) insted i get an error that choice_values is undefined.
My loop is:
function gotData(data){
var i = 0;
var statusFind = data.records[i].status;
for(i = 0; i < data.records.length; i++) {
var returned = [data.records[i].form_values["6f71"], data.records[i].form_values.b059, data.records[i].form_values["94d5"], data.records[i].form_values.b62d, data.records[i].form_values["3493"].choice_values["0"], data.records[i].status, data.records[i].form_values.af80];
for (j = 0; j < returned.length; returned++){
if (returned[j] == searchKey) {
var result = [returned[0], returned[1], returned[2], returned[3], returned[4], returned[5], returned[6]];
array.push(result);
write();
}
}
}
}
I used the Gson library to create a json from java and it returns me something like that:
[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]
How can I parse and access to the values in my js file?
i use a lot w3schools site here
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>JSON Object Creation in JavaScript</h2>
<p id="demo"></p>
Getting these is actually pretty easy in JS because JSON Objects are just considered Objects by js.
You can do this like so:
for (let i = 0; i < myArray.length; i++) {
let currObj = myArray[i];
let keys = Object.keys(currObj);
for (let j = 0; j < keys.length; j++) {
let myValue = keys[j];
doSomethingWithMyValue(myValue);
}
}
That will get every value for every key in every object in your array. This should give you a pretty good baseline for how these objects work.
Edit: Worth noting, there is also a Object.values(obj), method, which will return a list of all the values in your object in order, but it currently has very poor browser support, so you are much safer using Object.keys and then iterating over the keys like I showed above.
It's hard to say what you want to do with the data, and whether or not there are duplicate titles, as in your example. However...
var a = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
a.forEach(function(v) {
doSomething(v.title, v.author);
});
should work
With a for loop
If you get the JSON as an array
var json = [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}];
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
If you get the JSON as a string
var string = '[{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}]';
var json = JSON.parse(string);
for (var i = 0; i < json.length; i++) {
console.log(json[i].title, json[i].author);
}
//Here an example ---
var elements=[{id:123, name:'lorem'},{id:456, name:'ipsum'},{id:998, name:'verrugas'}];
for (item in elements){
console.log(elements[item].name);
}
Ok, that was a very noob question.
Firstly, to access to the values I have to do something like
data.title
In my case I had an array so I had to use something like
var j = JSON.parse(data);
for (var i = 0; i < j.length ; i++) {
console.log(j[i].title);
}
When I run for the first time this function it said "JSon unexpected identifier Object, that because Gson was returning already a json and javascript was trying to create a json of a json, so I removed the JSON.parse(data) and now it works!
Thanks u all
var AppPatientsList = JSON.parse(JSON RESPONSE);
var AppPatientsListSort = AppPatientsList.sort(function(a,b){
return a.firstName.toLowerCase() <b.firstName.toLowerCase()
? -1
: a.firstName.toLowerCase()>b.firstName.toLowerCase()
? 1 : 0;
});
var DataArray = [];
for (var i = 0; i < AppPatientsListSort.length; ++i) {
if (AppPatientsListSort[i].firstName === search.value) {
var appointment = {};
appointment.PatientID = AppPatientsListSort[i].PatientID;
appointment.ScheduleDate = AppPatientsListSort[i].ScheduleDate;
alert(appointment.ScheduleDate); // Works fine, i get the date...
}
DataArray[i] = appointment;
}
var RowIndex = 0;
var ScheduleDate = "";
for (i = 0, len = DataArray.length; i < len; i++) {
// Throws me error in this place... WHY?
if (ScheduleDate != DataArray[i].ScheduleDate) {
ScheduleDate = DataArray[i].ScheduleDate;
}
}
What's wrong with this code, why i am not able to access the ScheduleDate?
You are only initializing the appointment variable when you are inside the if clause, but you are adding it to the array on every iteration.
If the first element of AppPatientsListSort does not have the value you search for, DataArray[0] will contain undefined.
In the second loop you then try to access DataArray[0].ScheduleDate which will throw an error.
Update:
Even more important, as JavaScript has no block scope, it might be that several entries in DataArray point to the same appointment object.
Depending on what you want to do, everything it takes might be to change
DataArray[i] = appointment;
to
DataArray.push(appointment);
and move this statement inside the if clause so that only appointments are added that match the search criteria.
Further notes: To have a look what your DataArray contains, make a console.dir(DataArray) before the second loop and inspect the content (assuming you are using Chrome or Safari, use Firebug for Firefox).