Cannot read property 'split' of null - javascript

I cannot display all the results because on the following channel there is no image and therefore I have the following message
$.get('https://wcf.tourinsoft.com/Syndication/3.0/cdt33/c616ab2a-1083-4ba0-b8e2-f7741e443e46/Objects?$format=json', function(data) {
//$.get('/json/ecranv2.json', function(data){
var blogs = data.value;
$(blogs).each(function() {
var manifs = this.Listingraisonsociale;
var ouverturecomp = this.Listinginformationsouverture;
var commune = this.Listingcommune;
var ouverture = this.Listingouverture;
var photos = this.Listingphotos;
//var datatest= this.Listingphotos;
let output = '';
let users = this.Listingphotos.split('$');
//var testsplit = split($);
for (var i = 0; i < users.length; i++) {
console.log(users[i]);
output += '<img src=' + users[i] + '?width=150&height=150&crop=1>';
}
$('.target').append('<p>' + manifs + '</p><span>' + output + '</span>');
});
});

The one index does not have a value for the property. It is null, so you need to check to see if it is null before you try to use split on it. A simple truthy check will work in this case.
let users = this.Listingphotos ? this.Listingphotos.split('$') : [];
With it in place:
$.get('https://wcf.tourinsoft.com/Syndication/3.0/cdt33/c616ab2a-1083-4ba0-b8e2-f7741e443e46/Objects?$format=json', function(data) {
//$.get('/json/ecranv2.json', function(data){
var blogs = data.value;
$(blogs).each(function() {
console.log(this);
var manifs = this.Listingraisonsociale;
var ouverturecomp = this.Listinginformationsouverture;
var commune = this.Listingcommune;
var ouverture = this.Listingouverture;
var photos = this.Listingphotos;
//var datatest= this.Listingphotos;
let output = '';
let users = this.Listingphotos ? this.Listingphotos.split('$') : [];
//var testsplit = split($);
for (var i = 0; i < users.length; i++) {
console.log(users[i]);
output += '<img src=' + users[i] + '?width=150&height=150&crop=1>';
}
$('.target').append('<p>' + manifs + '</p><span>' + output + '</span>');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="target"></div>

split is a method on string objects, which will be called on an actual string's reference.
So in your case, the split is not being called on a string, and the error message clearly states that we are using split over a null object. So make sure the object you are working on is an actual string, and work on it accordingly.
split mdn

Related

Retrieve NGUCID from Rally

I am trying to retrieve custom NGUCID field from Rally but when I try to display it I get a value of "undefined". I have tried a few different options such as changing the type to PortfolioItem and Artifact. But it seems to me that the main issue is happening when I am dereferencing the object.
Here's my code:
function defectsExample() {
var displayDefects = function(results) {
var defectsInfo = "";
var defect = "";
var num;
var swpCounter = 0;
var storyCounter = 0;
var re = new RegExp('SWP');
for (i=0 ; i < results.defects.length ; i++) {
defect = results.defects[i];
storyCounter++;
// if ((re.test(defect.Name)) == true) {
defectsInfo += defect.Name + '<br>' + defect.NGUCID;
swpCounter++;
// }
}
var aDiv = document.getElementById("aDiv");
// aDiv.innerHTML = '<strong>Name, State, Severity</strong><br/>';
defectsInfo += 'Number of SWP stories: ' + swpCounter + '<br>';
defectsInfo += 'Total number stories: ' + storyCounter + '<br>';
aDiv.innerHTML += defectsInfo;
};
var queryConfig = {
/* type : 'HierarchicalRequirement',
key : 'defects',
query: '((Iteration.Name = "Sprint 40") AND ((Project.Name contains "CRM") OR (Project.Name contains "AR")))',
fetch: true //'Name, AcceptedDate'*/
type : 'HierarchicalRequirement',
key : 'defects',
// query: '(Iteration.Name = "Sprint 39")',
//query: '(NGUCID contains "1")',
fetch: 'Name,FormattedID,Project,NGUCID'
};
var rallyDataSource = new rally.sdk.data.RallyDataSource('__WORKSPACE_OID__',
'__PROJECT_OID__',
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
rallyDataSource.findAll(queryConfig, displayDefects);
}
rally.addOnLoad(defectsExample);
NGUCID is not a standard Rally field, so I assume it is one that you, or your organisation, have added as a Custom Field on the defect artefact type. All custom fields are accessible if the name is prefixed with 'c_'. In your case, it might be that you need to use "defect.c_NGUCID"
If you go to the WSAPI docs (https://rally1.rallydev.com/slm/doc/webservice/) it will show you the field names available to you for the various artefact types.

Unable to parse json using javascript

I have a json which i'm trying to parse it using javascript. Iteration count and the pages getting appended to it are going to be dynamic.
Expected Result
Just like the above image i'm able to take dynamic iteration keys from the below mentioned json.
Iteration.json
{
"count":[
{
"iteration1":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
},
{
"iteration2":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
}
]
}
When i click on iteration it has to populate the corresponding pagenames for that particular iteration as shown in expected result image. But what i get actually is (refer the image below):
Please find the code that i tried:
var pagenamearray = [];
$.getJSON("iteration.json", function(json) {
var hits = json.count;
var iterations, tnname, iteration;
for (var k in hits) {
var value;
if (hits.hasOwnProperty(k)) {
value = hits[k];
var iteratearray = [];
for (var j in value) {
if (value.hasOwnProperty(j)) {
j;
var check = value[j];
for (var i in check) {
if (check.hasOwnProperty(i)) {
var test = check[i];
for (var t in test) {
if (test.hasOwnProperty(t)) {
var pagename = JSON.stringify(t)
var arr = []
if (pagename.includes("PageName")) {
//alert("Key is " +pagename + ", value is" + JSON.stringify(test[t]));
for (var it = 0; it < hits.length; it++) {
if ((Object.keys(hits[it])).includes(j)) {
var pagenamevalue = test[t];
arr[it] = [];
arr.push(pagenamevalue);
}
}
}
//alert(arr)
}
pagenamearray.push(arr);
}
}
}
}
var row = document.createElement('div');
row.setAttribute("class", "row");
row.setAttribute("id", j)
var gridWidth = document.createElement('div');
gridWidth.setAttribute("class", "col-lg-12");
var panelRoot = document.createElement('div');
panelRoot.setAttribute("class", "panel panel-default");
var panelHeading = document.createElement('div');
panelHeading.setAttribute("class", "panel-heading");
var heading3 = document.createElement('a');
heading3.setAttribute("class", "panel-title");
var icon = document.createElement('i');
icon.setAttribute("class", "fa fa-long-arrow-right fa-fw");
heading3.appendChild(icon);
heading3.innerHTML = j;
heading3.setAttribute("onclick", "doit('" + j + "');");
panelHeading.appendChild(heading3);
/* var panelBody=document.createElement('div');
panelBody.setAttribute("class","panel-body");
panelBody.setAttribute("id","panellinks");*/
panelRoot.appendChild(panelHeading);
// panelRoot.appendChild(panelBody)
gridWidth.appendChild(panelRoot);
row.appendChild(gridWidth);
document.getElementById("analysis").appendChild(row);
}
}
}
});
function doit(value) {
var ul = document.getElementById(value);
if (ul != undefined) {
$("#" + "expandlinks").remove();
$("#" + value + value).remove();
}
var accordion = document.getElementById(value);
var panelBody = document.createElement('div');
panelBody.setAttribute("class", "panel-body");
panelBody.setAttribute("id", "expandlinks")
var tablediv = document.createElement('div')
var tablelink = document.createElement('a');
tablediv.appendChild(tablelink);
var graphdiv = document.createElement('div')
var graphlink = document.createElement('a');
graphdiv.appendChild(graphlink);
var recommndiv = document.createElement('div');
var recommendlink = document.createElement('a');
recommndiv.appendChild(recommendlink)
//alert(pagenamearray.length)
tablelink.innerHTML = pagenamearray;
/*graphlink.innerHTML="Timeline View";
recommendlink.innerHTML="Recommendations";*/
panelBody.appendChild(tablediv);
panelBody.appendChild(recommndiv);
panelBody.appendChild(graphdiv);
accordion.appendChild(panelBody);
}
Any advise on how to achieve this would be of great help. Thanks in advance.
I think the problem is how you assign the pagenamearray to tablelink.innerHTML. This converts the array to a string, converting all elements in the array to a string too and separating them by a comma each. However, your pagenamearray contains some empty arrays too; these will convert to an empty string in the process, but will still have a comma before and after them.
In your example code above, the pagenamearray will end up with a value of [[[],"T01_Launch"],[[],"T02_Login"],[null,[],"T01_Launch"],[null,[],"T02_Login"]] - when converted to a String, this will result in ",T01_Launch,,T02_Login,,,T01_Launch,,,T02_Login". So instead of assigning it to the innerHTML value directly, you'll first have to filter out the empty arrays and null values.

JSON input string error using $.ajax

My web API accepts below JSON format (this is input parameter)
[{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"},
{
"atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe",
"atrSpaClassLegendId": "00D18EECC47E7DF44200011302",
"atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"
}
]
I am building request below in javascript.
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe'
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c'
var atrUserLegendsInputs
for (i = 0; i < list.get_items().get_count() ; i++)
{
atrUserLegendsInputs += { atrSpaUserId: administratorId, atrSpaClassLegendId: list.getItem(i).get_value(), atrSpaCityDistrictId: districtId } + ',';
}
atrUserLegendsInputs = atrUserLegendsInputs.substring(0, atrUserLegendsInputs.length - 1);
var legendIds = '[' + atrUserLegendsInputs + ']';
var atrDistrictLegend = { districtID: cityDistrictId, legendIDs: legendIds };
var test = JSON.stringify(atrDistrictLegend);
getting error message:
{["The input was not valid."]}
I am not sure whether I am doing the right way. I am new to Json and ajax calls. Can you one please help me to fix this issue
Try this code
var administratorId = '47fe8af8-0435-401e-9ac2-1586c8d169fe';
var districtId = '144d0d78-c8eb-48a7-9afb-fceddd55622c';
//* create empty array for legends
var atrUserLegendsInputs = [];
for (i = 0; i < list.get_items().get_count() ; i++) {
//* put some values into legends' array
atrUserLegendsInputs.push({
atrSpaUserId: administratorId,
atrSpaClassLegendId: list.getItem(i).get_value(),
atrSpaCityDistrictId: districtId
});
}
var atrDistrictLegend = {
districtID: cityDistrictId,
legendIDs: atrUserLegendsInputs
};
var test = JSON.stringify(atrDistrictLegend);

Foreach element Javascript json

I got a JSON like this:
{
"email.com": ["email#email.com|username\r"],
"email.de": ["email#email.de|username"]
}
I want to get it printet like this:
email.com
email.de
var data = '{"email.com":["email#email.com|username\r"],"email.de":["email#email.de|username"]}';
var obj = JSON.parse(data);
for (i = 0; i < obj.length; i++) {
document.getElementById('types').innerHTML += '<br>' + obj[i]; // I want to get email.com , email.de
}
<div id="types">
</div>
This works fine:
var data = '{"email.com":["email#email.com|username\\r"],"email.de":["email#email.de|username"]}';
var obj = JSON.parse(data);
var keys = Object.keys(obj);
for (i = 0; i < keys.length; i++) {
document.getElementById('types').innerHTML += '<br>' + keys[i]; // I want to get email.com , email.de
}
<div id="types"></div>
var data = [{"email.com":["email#email.com|username\r"],"email.de":["email#email.de|username"]}];
var term = (Object.keys(data[0])[0]);
var obj = JSON.parse(data);
for (i = 0; i < obj.length; i++) {
document.getElementById('types').innerHTML += '<br>' + obj[i][term]; // I want to get email.com , email.de
}
This should work
Printing object's keys and values
Simple solution using String.match and Array.join functions:
var data = '{"email.com":["email#email.com|username\r"],"email.de":["email#email.de|username"]}',
emails = data.match(/\w+\.\w+(?=\":\[)/g).join("<br>");
document.getElementById('types').innerHTML += '<br>' + emails;
// 'emails' variable contains "email.com<br>email.de"
<div id="types"></div>
quickly :
var obj = {
"email.com": ["email#email.com|username\r"],
"email.de": ["email#email.de|username"]
};
for (var prop in obj) console.log(prop);

Writing from a custom type to an array in Javascript

I've been stuck for a few days now on this. I can get my albums to write to the console but I can't figure out how to get them to write into an array. The code works so when I click "Show Albums" button, it returns nothing other than [Object, object]. Can anyone help me figure out how to write the new albums to the array so it displays properly? Thanks in advance.
(function() {
var name = document.getElementById("name");
var year = document.getElementById("year");
var showbutton = document.getElementById("showlist");
var submitbutton = document.getElementById("submit");
var validate = document.getElementById("validate");
var albumlist = [];
var albums = function album(name, year) {
this.name = name;
this.year = year;
this.album = function() {
return ((this.name + ", " + this.year));
};
}
albums.prototype.genre = "rock";
var album1 = new albums("album1", "1999");
var album2 = new albums("album2", "2000");
var album3 = new albums("album3", "2001");
var album4 = new albums("album4", "2002");
var album5 = new albums("album5", "2003");
albumlist.push(album1, album2, album3, album4, album5);
showbutton.onclick = function() {
for (var i = 0; i < albumlist.length; i++) {
console.log(albumlist[i]);
}
document.getElementById("myalbums").innerHTML = albumlist.sort() + "<br/>";
}
document.getElementById("myalbums").innerHTML = albumlist.sort() + "<br/>";
Take a look at what this line does. This takes an array, which is an object with many functions, keys, etc, and tries to plot in on the page.
It will not be possible, since javascript doesn't know how to turn that array into a string.
For you to do that, you have to first create the string you want and than plot it on the page.
You need to iterate through the items and generate a string, for example:
var names = "";
for(var i = 0; i < albumlist.length; i++){
names += albumlist[i].name + ' ';
}
and then replace it on the html:
document.getElementById("myalbums").innerHTML = names + "<br/>";

Categories

Resources