Why is Data Null? - javascript

I came across an error today, and I am not sure why it occurred. At the second for loop, the access to data will be undefined instead of the data that was inserted as a parameter into the function. Somehow the data gets the value of null, instead of the Object that was passed to this function. Does anyone know why? The error I get is "data is not defined".
createDataObject: function (data) {
let dataObj = data.source[0];
let backedData = data.backedData;
for (let i in dataObj) {
let d = dataObj[i];
d.data = { source: d.data };
}
for (let i = 0; i < data.backedData.length; i++) {
let bd = data.backedData[i]; //<- this is where the error occurrs
let data = bd.data[0];
}
}
Here is some code outside of the object, if you want to try, that I was using, this will work on your console or in node. Seems like I have come across a Javascript compiler bug. I am not sure.
createDataObject({source: [[{data: 1}]], backedData: [1,2,3, 4]});
The code above will work if I do the following
createDataObject: function (data) {
let dataObj = data.source[0];
let backedData = data.backedData; //create the backedData variable here
for (let i in dataObj) {
let d = dataObj[i];
d.data = { source: d.data };
}
for (let i = 0; i < backedData.length; i++) {
let bd = backedData[i]; // no Error
let data = bd.data[0];
//.....
}
}

in the second for loop you create another data object. Data is not created on the first line in the for loop.
Try using
for (let i = 0; i < data.backedData.length; i++) {
let bd = data.backedData[i];
let d= bd.data[0]; // Convert data to d or another variable name
//.....
}

Related

Cannot push JSON elements to array inside for loop called from useEffect

I have an array candleRealTimeDataQueue which is not getting updated properly. Please find the code below:
let candleCurrentJSONDataWS = null;
var candleRealTimeDataQueue = [];
let tempDateTime = null;
let candleJsonData = {};
useEffect(() => {
getDataFromAPI();
}, []);
...
const getDataFromAPI = async () => {
let apiDataFetch = await fetch('https:/api/endpoint');
let response = await apiDataFetch.json(); // data from api obtained correctly
// total 4 values
for (var i = 0; i < 4; i++) {
tempDateTime = new Date(parseInt(response[i][0]));
candleJsonData['time'] = tempDateTime.toString();
candleJsonData['open'] = parseFloat(response[i][1]);
candleJsonData['high'] = parseFloat(response[i][2]);
candleJsonData['low'] = parseFloat(response[i][3]);
candleJsonData['close'] = parseFloat(response[i][4]);
console.log(candleJsonData); // this correctly prints different
// data for each different i
candleRealTimeDataQueue.push(candleJsonData);
console.log(candleRealTimeDataQueue); // PROBLEM is here: At the end
// candleRealTimeDataQueue array all
// have SAME elements. Its wrong. All
// 4 elements are of i = 3
}
}
Problem is at the end candleRealTimeDataQueue has 4 elements and all the elements are same. This should not happen because I am pushing DIFFERENT candleJsonData elements in the candleRealTimeDataQueue array in the for loop. Please help.
I believe the problem here is that you are reusing the candleJsonData object. When you run candleRealTimeDataQueue.push(candleJsonData), you are pushing the reference to candleJsonData into candleRealTimeDataQueue. So at the end of the loop, you have four references to the same object inside candleRealTimeDataQueue. And since you are modifying the same candleJsonData object over and over again, you'll just see four identical json data inside the queue when you log it and all four elements will be of i = 3.
Instead, you should be creating new candleJsonData objects inside your loop. So something like
for (var i = 0; i < 4; i++) {
tempDateTime = new Date(parseInt(response[i][0]));
let candleJsonData = {}
candleJsonData['time'] = tempDateTime.toString();
candleJsonData['open'] = parseFloat(response[i][1]);
candleJsonData['high'] = parseFloat(response[i][2]);
candleJsonData['low'] = parseFloat(response[i][3]);
candleJsonData['close'] = parseFloat(response[i][4]);
candleRealTimeDataQueue.push(candleJsonData);
}
it is because of the candleJsonData variable which is declared outside, so latest value is overriding previous value. In face there is no need of that variable and it can directly push in the array.
var candleRealTimeDataQueue = [];
React.useEffect(() => {
getDataFromAPI().then((data) => {
for (let i = 0; i < 4; i++) {
candleRealTimeDataQueue.push({
time: new Date(parseInt(data[i][0])).toString(),
open: parseFloat(data[i][1]),
low: parseFloat(data[i][3]),
close: parseFloat(data[i][4]),
});
}
});
return () => {
// do clean up here
};
}, []);
const getDataFromAPI = () => {
return fetch('https:/api/endpoint');
};

Javascript - Help retrieving data from Firebase

I have this code below to retrive data from firebase and turn into an array but whenever i call it it stops other functions from being called inside the code even tho I can perfectly call them in the console.
I've worked around this by using callback functions but I am at a point it just doesn't do anymore. How can make this part act like a normal function where I can call anytime without stopping the code.
function genList(){
dataRef.on('value', data => {
let arr = (data.val());
let keys = Object.keys(arr);
for (let i = 0; i < keys.length; i++) {
let k = keys[i];
let title = arr[k].title;
let author = arr[k].author;
let pages = arr[k].pages;
let date = arr[k].date;
let bookmark = arr[k].bookmark;
let newList = new Object();
newList.title = title;
newList.author = author;
newList.pages = pages;
newList.date = date;
newList.bookmark = bookmark;
bookList.push(newList);
}
})}

Reading data from Firebase to Javascript

I am trying to list all data from Javascript keys Object when I put it in console log there is all information, but when I want to use InnerHTML I keep getting the first object only shown.
function gotData(data){
var scores = data.val();
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var pro = scores[k].result;
var doc = document.getElementById("result").innerHTML = pro;
}
}
In this case, it will give me only a result of first element from my Firebase
Thanks
Please check out this stackblitz-demo, looks like your missing one small thing if I am understanding what your expected outcome is.
onClick() {
const scores = [{
'one': 1
}, {
'two': 2
}, {
'three': 3
}, {
'four': 4
}, {
'five': 5
}];
var keys = Object.keys(scores);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
const pro = scores[k].result;
// here the += is what i think you're missing.
const doc = document.getElementById("example").innerHTML += k;
}
}
The issue is that you are overriding innerHTML each time. Instead, you need to append to the existing innerHTML. Change the last line to...
const doc = document.getElementById("example").appendChild(document.createTextNode(k))
appendChild is also much faster than setting innerHTML
.hasOwnProperty is how to see just your stored values. Does this help?
d = snap.val();
for (var k in d) {
if (d.hasOwnProperty(k)) {
if (isObject(d[k]){
console.log(k, d[k]);
} else {
console.log (k);
}
}
}
function isObject(obj) {
return obj === Object(obj);
}

js Array undefined after json declaration

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;
}

Constructing json object using javascript

I am facing issues while constructing an object using javascript. I want this:
{
"p_id": "2",
"p_name": "weblogic",
"ip_list": [
{
"ip_id": 2690
},
{
"ip_id": 2692
},
{
"ip_id": 2693
}
]
}
Below is the javascript code that I am using to get the data into the object:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push("ip_id": selectedArray[index]);
}
I am able to construct the properties for p_id and p_name but struggling to create the the ip_list. Please let me know how to get this constructed using javascript.
Code for posting to the server:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = 2;
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
console.log (secTagJSON);
console.log (JSON.stringify(secTagJSON));
$http.post("http://server:port/api/v1/tags").
success(function(data) {
console.log (data)
});
Simply do this:
var obj = { ip_list: [] };
obj.p_name = "weblogic";
obj.p_id = "2";
for (var i = 0, j = selectedArray.length; i < j; i++)
obj.ip_list.push({ ip_id: selectedArray[i] });
Note that your ip_list is actually an array of objects. So, when you iterate over it, remember that each var item = json.ip_list[i] will return an object, that you can access its properties using: item['ip_id'].
Note that obj is an Javascript object, it is not an JSON. If you want the JSON, you can use JSON.stringify(obj). This will return your JSON (string).
Hope I've helped.
Try:
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
secTagJSON.ip_list = [];
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
you forgot your {} around "ip_id": etc...
You also need to declare that ip_list is an array.
Your ip_list is an array of objects. I would guess that your script was not running as it was.
Posting to your server you should use:
$http.post('server:port/api/v1/tags', secTagJSON).sucess(...

Categories

Resources