remove:function line while Printing Array in Console - Javascript - javascript

Using Chrome.
I've got a multidimensional array 'stories'
I'm printing 'stories' using console.log(stories);
Console log shows me all 24 elements of 'stories' in the console, but the first line of the console expansion arrow shows [remove:function]
When I try to print out to the console an individual array element using console.log(stories[2]);, it doesn't work. The console prints out undefined.
So, printing all array elements works just fine, but printing out an individual element doesn't.
Any idea what may be happening?
My end goal is to sort this array, and it is not working right now, and I am thinking that these issues are related.
Any advice greatly appreciated! thanks!
Further info:
I'm making an array and then passing elements into the array. each element is a sharepoint list item.
var stories = new Array();
getMyGPShareListData(".../ListProxy.html?listname=NewsArticles&odata=%24top%3D3%26%24orderby%3DArticleDate%20desc", { success: successGPNowData, error: errorGPNowData });
function successGPNowData(data) {
//Handle SharePoint REST List Items
if (data.d) {
iReturns = iReturns + 1;
//Determine data results to pass to top nav
jQuery.each(data.d, function (n, item) {
item.ArticleDate = item.ArticleDate.substr(6).replace(")/","");
stories.push(item);
});
}
}

Related

Realm object list functions are undefined, even though object is defined and list is populated

Trying to push a new int into an int realm list. I can get the Realm object, I can print it and when I print the object it shows the list with it's content, I can use Realm Studio to edit, add numbers to the list, etc.. But when I try to call any methods form the list it says it is undefined.
Have tried async, await, then, though it was a synchronization issue, but doesn't seem like it.
The code below is similar to mine, but edited to hide the original names, etc, and does not have all the properties from the original, but it does not change the behave for the specific list I am trying to edit. Everything else works fine.
I have an schema like
let mySchema={
name:'MySchema',
properties:{
my_schema_id: 'string',
numbers: 'int[]'
}
The function to create a new object is
Realm.open({schema: [mySchema]})
.then(realm => {
realm.write(() => {
realm.create('MySchema', {my_schema_id: `${my_schema_id}`, numbers: [parseInt(number, 10)]});
});
I try to add a number with:
Realm.open({schema: [mySchema]})
.then((realm) => {
let fetchedSchema = realm.objects('MySchema').filtered(`my_schema_id ="${my_schema_id}"`);
console.log(fetchedSchema);
realm.write(()=>{
fetchedSchema.numbers.push(parseInt(number, 10));
});
And it gives an error:
(node:73249) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
I expected to push the item to the list, or to be able to call the list functions. Instead, when I try to use the list it shows as undefined even though I can see it and it's content when I print the object...
Found a solution.
Querying let fetchedSchema = realm.objects('MySchema').filtered(my_schema_id ="${my_schema_id}"); actually returns an array of elements, so I just had to select the first with [0]at the end

Logger.log shows all of the nested array values, but the sheet only gets the first item added

The API I am accessing has an array (tickets), that contains a nested array of strings (tags). When I loop through to get to the nested array values, I am able to see the full list of tags (in the red box of the screenshot below).
When I view the sheet, however, it is only returning the first item of the array as you can see in the below screenshot.
I am sure this is something silly, but I cannot figure it out. My code is below. Thank you for any help you can provide.
var example = []
results.forEach(function(tickets){
var temp = [];
tickets.tags.forEach(function(tags){
temp.push(tags);
})
example.push([tickets["resolution_time"],tickets["created_at"], tickets["priority"], tickets["state"],tickets["id"], tickets["closed_by"], temp])
})
Logger.log(example + "is this working?");
var len = example.length;
//clear existing data
sheet.getRange(2,1,2000,8).clearContent();
//paste in the values
sheet.getRange(sheet.getLastRow() +1,1,len,7).setValues(example);
I see you trying to put an array of strings (temp) into a single cell of the sheet. Can you even do that?
Replace
var temp = [];
tickets.tags.forEach(function(tags){
temp.push(tags);
})
with
var temp = tickets.tags.join(',')

Strange behavior when removing an item from Array in Polymer 1.x

Suppose there's an array called '_arr' from which I remove an item. Before removing though I log it to console. Problem is that log shows the array as if the item is removed already. I have reviewed data system in Polymer Documentation and still scratching my head.
Am I missing something on how data system works or I should be looking somewhere else for the cause?
EDIT: _arr is an array of strings and I am passing an event like:
this.fire('rmv-item' , {item: 'item content which is string'});
Here's the code
_removeItemFromArr: function(e) {
const index = this._arr.indexOf(e.detail.item) ;
console.log('array before remoivng item:' , this._arr , index); //item doesn't exist
if (index>-1) { this.splice('_arr' , index, 1 }
console.log('array after removing item: ' , this._arr , index); //item doesn't exist
},
The problem is that things are doing exactly what you say: the console logs the array, it most emphatically does not log the array "as it was at some specific time in the past", it logs the array as it is when log actually runs. And because the logging operation is not synchronous, by the time it actually writes the crosslinked reference and symbol-table-linked data to the browser console, you already removed the data from the array, so what you see is what console.log sees when it actually kicks in.
If you want a true snapshot of what your array ways "when you call log", don't log the array, log a copy of the array, which is guaranteed to generate synchronously using something like slice():
const index = this._arr.indexOf(e.detail.item);
console.log(`array before removing item at [${index}]: ${this._arr.slice()}`);
And job's a good'n.

Array push yields unexpected array

Simple question I hope (not sure what I am missing);
How can I push items to a basic and not an indexed array?
When doing this:
var shops = [];
angular.forEach(data, function(value, index) { //loop over data
shops.push(value.SHOP_CODE);
});
When you are logging the shops array to console, the array is probably empty and hence it says Array[0].
The contents of the array are evaluated again when you click the dropdown arrow beside Array[0]. So at the time of your click on the dropdown the array is not empty and hence showing 4 elements.
If the array were not empty at the point where you do console.log(shops), then you would get the result you are looking for.
I suggest you add a breakpoint at the statement console.log(shops) and check the contents of the array.
Thanks to #Patrick Evans and #SLePort, I realized I needed to wait for the promise. This works:
.$promise.then(function(data) {
$scope.workOrder = data;
angular.forEach(data, function(value, index) { //loop over aircraft data
shops.push(value.SHOP_CODE);
});
shops.sort();
console.log(shops);
});

Working with a JSON file and Javascript

On return of a JSON file I can't seem to be able to detect how many results are returned. The problem seems to be with the JSON file returning a diffrent number of items each time. At times it will return 1 item, then at other it will return more than 1. You see, I'm trying to get the very first result from the JSON file so I can display it. Now, If change the code everytime I know the number that will be returned, the following two bits of code work.. Artists.id; and Artists.id[0];, but I can't seem to make them work together, at the momment..
If 1 result is returned, Artists.id; will successfully bring back the artist ID;
If more than 1 result is returned Artists.id; will return "undefined".
So I need to change it to Artists.id[0]; if the JSON file returns more than 1 item. However when I change it to this, if the JSON conatins 1 item, it will return "undefined".
It seems I need some code to tell me if the returned array has 1 or more items. I've tried arr.length but that doesn't seem to be working (perhaps i miss-coded it). I also tried if(arr===undefined) and that failed to work too. The code below is what I have come up with, using the artistzero, but it is not working. Anyone has any advice? or a reason why the code below would not work?
Current Code:
$.ajax(
{
type: "GET",
url: id_url,
dataType: "jsonp",
success: function (responseData, textStatus, XMLHttpRequest)
{
if (responseData.Artists.Artist)
{
var Artists = responseData.Artists.Artist;
var artistzero = Artists.length;
if (artistzero >= 2)
{
// if more than one result is returned
var artisttype = Artists.id[0];
}
if (artistzero <= 1)
{
// if one result is returned
var artisttype = Artists.id;
}
}
else
{
$('body').append('No results');
}
}
});
Sample JSON with 1 result:
{"Artists":{"total":"1","count":"1","start":"1","errorCount":"0","Artist":{"id":"33291476","flags":"123010","catzillaID":"0","website":"","name":"Jamie T","rating":"-1","ItemInfo":{"Relevancy":{"index":"1316"}},"hotzillaID":"1809709440","url":"http://web.com/jamie-t/","trackCount":"96"}}}
Sample JSON with more than one result:
{"Artists":{"total":"1087","count":"3","start":"1","errorCount":"0","Artist":[{"id":"256212","flags":"123523","catzillaID":"1927205428","website":"http://www.bobmarley.com/","name":"Bob Marley","rating":"-1","ItemInfo":{"Relevancy":{"index":"718"}},"hotzillaID":"1802045595","url":"http://web.com/bob-marley/","trackCount":"12706"},{"id":"312874","flags":"124611","catzillaID":"1927580000","website":"http://www.bobdylan.com/","name":"Bob Dylan","rating":"-1","ItemInfo":{"Relevancy":{"index":"694"}},"hotzillaID":"1800021697","url":"http://web.com/bob-dylan/","trackCount":"4987"},{"id":"268472","flags":"41603","catzillaID":"1927193413","website":"","name":"Bob Wills","rating":"-1","ItemInfo":{"Relevancy":{"index":"644"}},"hotzillaID":"1800264434","url":"http://web.com/bob-wills/","trackCount":"2364"}]}}
You need to access the first artist before grabbing the id (since it's an array) like this:
var artisttype = Artists[0].id;
It would be better if you could change the JSON to always return an Array, even with one result...unfortunately some platforms don't do this, for reasons beyond my comprehension.
for(var propertyname in responseData){
//will loop through the different elements in your json array
alert(responseData[propertyName]); //will output the valueof each element
}
You're right that this is problematic, and to be honest it sounds like the "other end" that's sending you the JSON is being inconsistent.
The problem is that when there are multiple items they're sending you an array for the id property, and when there's a single item they're just sending you a simple value (e.g. an integer). Ideally, when there is a single item you should be sent a single-item array - this would let you use the same array-based parsing code every time.
If you can't convince them to change what they're sending you, though, then the best bet is simply to do what you're currently doing; see if Artists.id is defined, use it if so, else fall back to accessing id as an array.
However, if more than 1 result is returned Artists.id; will return "undefined". So I need to change it to this: Artists.id[0];
this cannot be Artists.id should be "object" not undefined if Artists.id[0] exists. Maybe it is as stated Artists[0].id ? and if so you could test typeof(Artists) == typeof([])

Categories

Resources