How do i push a variable after using split function in javascript? - javascript

error: Uncaught (in promise) TypeError: Cannot read property
'push' of undefined error line: " this.name[i].push(arrayData[0]);
"
I do not understand since the line before console.log("data is loaded:" + arrayData[0]); is working!
Is it something about async? Can someone please help me out?
Here is my code:
data: {
name: []
},
methods: {
LoadData: function() {
console.log("onload fundtion. \n");
fetch('http://localhost/store/skininfor.txt')
.then(response => response.text())
.then((data) => {
// console.log(data);
var textByLine = data.split("\n");
for (var i = 0; i < textByLine.length; i++) {
var arrayData = textByLine[i].split(",");
console.log("data is loaded:" + arrayData[0]);
if (arrayData[0] !== undefined) {
this.name[i].push(arrayData[0]);
}
}
});
},

By this way this.name[i].push(arrayData[0]); you are trying to push an element into another element this is why you have that error.
this.name is the tab and this.name[i] is one element so it should be this.name.push(arrayData[0]);

you don't have any element in the name array therefore you should push like this.
this.name.push(arrayData[0]);

You probably need to assign instead of pushing, i.e.
this.name[i] = arrayData[0];
(Although I can't be sure. If you defined example input data and desired output, that would be helpful).

Related

HTML page is not showing the info I need from json file

My script, this should be showing the Name of game computers in html but it does not, I have been trying so much andI betit will just be something stupid that is wrong or missing
Console says : TypeError: data is undefined
The console does show me retrieving the data works
"use strict";
window.addEventListener("load", Init);
function Init() {
fetch("https://howest-gp-wfa.github.io/st-2021-1-S2-a-wfa-pe03-Jonas-Bundervoet/api/products.json")
.then(function(response) { return response.json(); })
.then(data => console.log(data))
.then(function(data){
tester(data)
})
.catch(err => console.log(err));
window.addEventListener("load", tester);
}
My function to show data on screen (shows nothing)
function tester(data)
{
let div = document.getElementById("test");
for (var i = 0; i < data.length; i++) {
let article = document.createElement("h1");
article.innerHTML = 'Name: ' + data.GameComputers[0].Name;
div.appendChild(article);
};
}
In HTML I just have this in my body
<div id="test"></div>
console.log returns undefined
.then(data => console.log(data))
.then(function(data){
tester(data)
Your first then returns the return value of console.log which is undefined.
So your second then recieves undefined as its data.
Don't use multiple then callbacks here.
.then(function(data){
console.log(data)
tester(data)
The JSON doesn't consist of an array
The JSON you are looking at returns an object.
It doesn't have a length.
for (var i = 0; i < data.length; i++) {
… is going to fail immediately.
You've got data.GameComputers[0] so I'm guessing you want to loop over GameComputers so:
Check the length of that: i < data.GameComputers.length
Make use of i when you read it: data.GameComputers[i].Name;

Uncaught (in promise) TypeError: n.join is not a function

I have an extension on devops azure, and I 'm newbie in Javascript by the way.
I wrote an function to get the name of task after fetch its id from server:
dataService.getDocument("registryKey").then((doc) => {
let authenToken = doc.value[doc.count - 1];
fetch('https://52.221.253.35/api/timelog'+query, {
method: 'GET',
headers:{
'Authentication': authenToken
}
}).then((resp) => resp.json()).then(function (data) {
let index = 1;
let body = "";
// foreach the data and i call VSS Http to get work item 's detail
data.forEach(async function f(item) {
let result = await witClient.getWorkItems(item.TaskId, ["System.Id", "System.Title"]);
body+="<p>"+result['System.Title']+"</p>"
$("#table-body").html(body);
});
but when it runs, it throws an error: Uncaught (in promise) TypeError: n.join is not a function
What is wrong here? Thank you for your comment.
Try this:
let result = await witClient.getWorkItems([item.TaskId], ["System.Id", "System.Title"]);
body+="<p>"+result['System.Title']+"</p>"
$("#table-body").html(body);
});
Note the square brackets around the first parameter.

Unable to appendChild data from a promise in javascript

I'm having problems when appending to the body the data returned by a promise. I console log it and everything seem to be working fine, however, when I try to do a simple appendChild to the body, I receive an error which says: "functions.js:73 Uncaught (in promise) TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'"
I looked this error up on the internet, here in StackOverflow and someone has already asked the same question, but the answer he got doesn't work for me.
Please, can you take a look and help me figure out what's wrong here?
Thanks.
fetchUsers()
.then(data => data.json())
.then(json => {
listUsers(json);
return fetchJanet();
})
.then(janetData => janetData.json())
.then(janet => listJanet(janet.data));
function fetchUsers() {
return fetch("https://reqres.in/api/users");
}
function listUsers(json) {
users = json.data;
users.forEach((element, i) => {
n = document.createElement("h3");
n.innerHTML =
element.first_name + " " + element.last_name + " have an index of: " + i;
document.body.appendChild(n);
document.getElementById("loading").style.display = "none";
});
}
function fetchJanet() {
return fetch("https://reqres.in/api/users/2");
}
function listJanet(element) {
console.log(element);
name = document.createElement("p");
name.innerHTML = element.first_name + " " + element.last_name;
document.body.appendChild(name);
}

TypeError: data.map is not a function

Im really stuck on this figuring out what did I miss, Im not that expert about javascript, if someone can please tell me what I did wrong, I really appreciate.
I have a working code:
if (value_ == "group") {
fetch("http://localhost/someapi"+value_).then(r => { return r.json()})
.then(json => {
var data = `{ "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] }`;
var data = JSON.parse(data);
var groupName = data.group.map(current => current.name);
var groupTag = data.group.map(current => current.tag);
console.log(data);
console.log(`json: ${data.group[0].name}`);
});
}
the code above will work and get every data I wanted, but the json is from the:
var data = `{ "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] }`;
then I tried to get the json from the URL which return the same value as the var data above. But it doesn' work.
which I did change var data = JSON.parse(data); into data = JSON.parse(json)
and delete "var data = { "group" : [{"name":"foo","tag":"bar"},{"name":"bool","tag":"lean"}] };"
And it does give an error: (node:10868) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected end of JSON input
I also tried this code:
fetch("http://localhost/someapi"+value_).then(r => { return r.json()})
.then(json => {
parseJSON(JSON.stringify(json));
function parseJSON(str){
var data = JSON.parse(str);
var groupName = data.group.map(current => current.name);
var groupTag = data.group.map(current => current.tag);
console.log(data);
console.log(`json: ${data.group[0].name}`);
}
});
}
this give me error: (node:12668) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined.
Thanks and pardon my english.
You don't need to execute JSON.parse manually because the content of json variable in the third line of your example is already an object.
Try this:
fetch("http://localhost/someapi"+value_)
.then(r => r.json())
.then(json => {
var groupName = json.group.map(current => current.name);
var groupTag = json.group.map(current => current.tag);
console.log('groupName', groupName);
console.log('groupTag', groupTag);
});

Why I get this error: Uncaught TypeError: Cannot read property 'serviceId' of undefined

I can display value of serviceId to console but when I try to compare it in if(), I got this error. Can you tell me why does this happend and how to solve it, please?
I also tried to put value of servicesCompare1[i].serviceId to variable and I got same error.
var servicesCompare1 = [];
var servicesCompare2 = [];
$.getJSON("http://localhost:55972/api/status", function (data) {
self.services(data.services);
self.lastCheck = data.lastCheck;
servicesCompare1 = (data.services);
});
function DashboardRefresh() {
self.servicesRefresh = ko.observable([]);
$.getJSON("http://localhost:55972/api/status", function (data) {
servicesCompare2 = (data.services);
self.servicesRefresh(data.services);
});
if (servicesCompare2.length > servicesCompare1.length) {
for (i = 0; i < (servicesCompare2.length-1); i++) {
console.log(servicesCompare2[i].serviceId);
if (servicesCompare1[i].serviceId !== servicesCompare2[i].serviceId) {
self.services.push(servicesCompare2[i]);
}
}
}
}
setInterval(DashboardRefresh, 5000);
Console output:
47
48
49
... other Ids
Uncaught TypeError: Cannot read property 'serviceId' of undefined
at DashboardRefresh (NetworkStatus.html:66)
Your first condition ensures that servicesCompare2 has more items than servicesCompare1. You're then looping through each item in servicesCompare2. This means that at some point, you're going to run into a situation where servicesCompare2 still has items left to traverse, while servicesCompare1 does not.

Categories