reading from csv file returns undefined value - javascript

For some reason, when I am reading a CSV file with React, I am getting undefined as the values, and I am not sure why this is happening. Below is the general format of my .csv file.
Date,Site,Depth (m),Temp (degC),SpeCond(uS/cm),Chla (ug/L),Turb (FTU),DO (mg/L)
Mar-18-2019,UA01,-0.518,10.9387,233.3824,4.2043,11.118,10.7842
Mar-18-2019,UA01,-0.585,10.9352,233.4042,4.4753,11.272,10.7935
Mar-18-2019,UA01,-0.651,10.9335,233.3973,4.641,11.26,10.7987
Mar-18-2019,UA01,-0.717,10.9319,233.4335,4.7184,10.985,10.796
Mar-18-2019,UA01,-0.785,10.9292,233.4137,4.8404,10.985,10.7938
Mar-18-2019,UA01,-0.85,10.9268,233.4009,5.0127,11.158,10.7885
Mar-18-2019,UA01,-0.909,10.9257,233.4585,5.1674,11.662,10.78
Mar-18-2019,UA01,-0.969,10.9248,233.4452,5.3253,11.249,10.7753
Mar-18-2019,UA01,-1.04,10.9241,233.3777,5.5321,10.852,10.7706
...
This is my App.js:
import React,{useState} from "react";
import * as $ from 'jquery';
import ReactDOM from 'react-dom'
import Highcharts from 'highcharts';
export default function App() {
const [selects, setSelects] = useState();
return (
<div className="App">
<h1>{selects}</h1>
<h3 className = "form-labels"> Visuals: </h3>
<select value = {selects} onChange = {e=>printSelected(e.target.value) }>
<option>Temperature</option>
<option>Special Conductivity</option>
<option>Chlorophyll</option>
<option>Turbosity</option>
<option>Dissolved Oxygen</option>
</select>
<select value = {selects} onChange = {e=>printSelected1(e.target.value) }>
<option>UA01</option>
<option>UA01_SB19</option>
<option>UA01_SB25</option>
<option>UA06</option>
<option>UA06_SB19</option>
<option>UA06_SB25</option>
<option>UA07</option>
<option>UA07_SB19</option>
<option>UA07_SB25</option>
<option>UA08</option>
<option>UA08_SB19</option>
<option>UA08_SB25</option>
<option>LA03</option>
<option>LA03_SB19</option>
<option>LA03_SB25</option>
<option>NR02</option>
<option>NR02_SB19</option>
<option>NR02_SB25</option>
<option>OA04</option>
<option>OA04_SB19</option>
<option>OA04_SB25</option>
</select>
</div>
);
}
const x = [];
const y = [];
var tab = [];
var tab1 = [];
var tab2 = [];
var tab3 = [];
var tab4 = [];
var response = "";
var data = "";
var sortedD = [];
var sortedD1 = [];
var sortedD2 = [];
var sortedD3 = [];
var sortedD4 = [];
var fileName = "UA01";
var visuals = "Temp";
function printSelected(e) {
sortedD.length = 0;
tab.length = 0;
sortedD1.length = 0;
tab1.length = 0;
sortedD2.length = 0;
tab2.length = 0;
sortedD3.length = 0;
tab3.length = 0;
sortedD4.length = 0;
tab4.length = 0;
visuals = e;
getChart();
}
function printSelected1(e) {
sortedD.length = 0;
tab.length = 0;
sortedD1.length = 0;
tab1.length = 0;
sortedD2.length = 0;
tab2.length = 0;
sortedD3.length = 0;
tab3.length = 0;
sortedD4.length = 0;
tab4.length = 0;
fileName = e;
getChart();
}
async function getChart() {
await getData();
var data1 = [];
var name1 = "";
if (visuals.localeCompare("Temp") === 0) {
data1 = sortedD;
name1 = "Temperature (deg Celsius) ";
} else if (visuals.localeCompare("Special Conductivity") === 0) {
data1 = sortedD1;
name1 = "Special Conductivity (uS/cm) ";
} else if (visuals.localeCompare("Chlorophyll") === 0) {
data1 = sortedD2;
name1 = "Chlorophyll (ug/L) ";
} else if (visuals.localeCompare("Turbosity") === 0) {
data1 = sortedD3;
name1 = "Turbosity (FTU) ";
} else {
data1 = sortedD4;
name1 = "Dissolved Oxygen (mg/L)";
}
}
async function getData() {
response = await fetch(fileName + ".csv");
data = await response.text();
const table = data.split('\n').slice(1);
table.forEach(row => {
const col = row.split(',');
const depth = col[2];
var ele = [];
var ele1 = [];
var ele2 = [];
var ele3 = [];
var ele4 = [];
console.log("Depth: " + depth);
console.log("Val: " + col[3]);
ele.push(parseFloat(col[3]));
ele.push(parseFloat(depth));
ele1.push(parseFloat(col[4]));
ele1.push(parseFloat(depth));
ele2.push(parseFloat(col[5]));
ele2.push(parseFloat(depth));
ele3.push(parseFloat(col[6]));
ele3.push(parseFloat(depth));
ele4.push(parseFloat(col[7]));
ele4.push(parseFloat(depth));
tab.push(ele);
tab1.push(ele1);
tab2.push(ele2);
tab3.push(ele3);
tab4.push(ele4);
})
sortedD = tab.sort((a,b) => b[0]-a[0]);
sortedD1 = tab1.sort((a,b) => b[0]-a[0]);
sortedD2 = tab2.sort((a,b) => b[0]-a[0]);
sortedD3 = tab3.sort((a,b) => b[0]-a[0]);
sortedD4 = tab4.sort((a,b) => b[0]-a[0]);
}
getChart();
I am trying to build a dropdown menu to display different line graphs depending on what dropdown is selected, but for some reason when I try to print values of my variables I am trying to plot, I get undefined. And the length of the arrays I have made are always 43 for some reason...
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
I have a feeling that it might be the await fetch and await response, but I am not 100% sure. Any tips on this would be greatly appreciated!

Related

Changing My working script to Dockable script does not work as expected

I have a working script for after effects, but when I change it to Dockable script,it wont work. Please help me to figure out why? If I take it out of the dock script it is working. I copied this dockable code from goodboy.ninja website.
This the final Dockable Code. Where is the mistake?
(
function(thisObj) {
buildUI(thisObj);
‍
function buildUI(thisObj) {
var windowName = "Diffrence Checker";
var myPanel = (thisObj instanceof Panel) ? thisObj : new Window("window", windowName, undefined, {
resizeable: true
});
// Dropdown list
var groupOne = myPanel.add("group", undefined, "groupOne");
groupOne.orientation = "row";
groupOne.add("StaticText", undefined, "Main Comp");
var mainDD = groupOne.add("dropdownlist", undefined, compArrayNames);
mainDD.size = [175, 25];
var groupTwo = myPanel.add("group", undefined, "groupTwo");
groupTwo.orientation = "row";
groupTwo.add("StaticText", undefined, "Diff File");
var diffDD = groupTwo.add("dropdownlist", undefined, VideoArrayNames);
diffDD.size = [175, 25];
// Button code
var createBT = myPanel.add("group", undefined, "createBT");
createBT.orientation = "column";
var mainbutton = createBT.add("button", undefined, "Create");
//myPanel.center();
//myPanel.show();
‍
myPanel.onResizing = myPanel.onResize = function() {
this.layout.resize();
};
if (myPanel instanceof Window) {
myPanel.center();
myPanel.show();
} else {
myPanel.layout.layout(true);
myPanel.layout.resize();
}
}
// Write your helper functions here
var compArray = [];
var compArrayNames = [];
var VideoArray = [];
var VideoArrayNames = [];
for (var i = 1; i <= app.project.numItems; i++) {
if (app.project.item(i).hasVideo == true && app.project.item(i).file == null) {
compArray.push(app.project.item(i));
compArrayNames.push(app.project.item(i).name);
}
if (app.project.item(i).hasVideo == true && app.project.item(i).hasAudio == true) {
VideoArray.push(app.project.item(i));
VideoArrayNames.push(app.project.item(i).name);
}
}
function createCP() {
app.beginUndoGroup("Editing");
var comlayer = compArray[mainDD.selection.index];
var vidlayer = VideoArray[diffDD.selection.index];
var getcomp = app.project.items.addComp(VideoArrayNames[diffDD.selection.index] + "_DIFF".toString(), 1920, 1080, 1, comlayer.duration, 30);
getcomp.openInViewer();
addVideofile(comlayer, getcomp);
addvideotwofile(vidlayer);
renderQ();
app.endUndoGroup();
}
function addVideofile(comlayer) {
app.project.activeItem.layers.add(comlayer);
}
function addvideotwofile(vidlayer) {
var newlayer = app.project.activeItem.layers.add(vidlayer);
newlayer.blendingMode = BlendingMode.DIFFERENCE;
}
function renderQ() {
var Qcomp = app.project.activeItem;
var Qitem = app.project.renderQueue.items.add(Qcomp);
}
}
)
(this);
My Original script is as follows:
// Diffrence Check
// global variables
var compArray = [];
var compArrayNames = [];
var VideoArray = [];
var VideoArrayNames = [];
for (var i = 1; i <= app.project.numItems; i++){
if (app.project.item(i).hasVideo == true && app.project.item(i).file == null) {
compArray.push (app.project.item(i));
compArrayNames.push (app.project.item(i).name);
}
if (app.project.item(i).hasVideo == true && app.project.item(i).hasAudio== true) {
VideoArray.push (app.project.item(i));
VideoArrayNames.push (app.project.item(i).name);
}
}
var mainWindow = new Window("palette","Difference Checker",undefined);
mainWindow.orientation= "column";
// Dropdown list
var groupOne = mainWindow.add("group",undefined,"groupOne");
groupOne.orientation = "row";
groupOne.add("StaticText",undefined,"Main Comp");
var mainDD = groupOne.add("dropdownlist",undefined,compArrayNames);
mainDD.size = [175,25];
var groupTwo = mainWindow.add("group",undefined,"groupTwo");
groupTwo.orientation = "row";
groupTwo.add("StaticText",undefined,"Diff File");
var diffDD = groupTwo.add("dropdownlist",undefined,VideoArrayNames);
diffDD.size = [175,25];
// Button code
var createBT = mainWindow.add("group",undefined,"createBT");
createBT.orientation = "column";
var mainbutton = createBT.add("button",undefined,"Create");
mainWindow.center();
mainWindow.show();
// Main Code Begins
mainbutton.onClick = function(){
createCP();
}
// Main Function Code
function createCP() {
app.beginUndoGroup("Editing");
var comlayer = compArray[mainDD.selection.index];
var vidlayer = VideoArray[diffDD.selection.index];
var getcomp = app.project.items.addComp(VideoArrayNames[diffDD.selection.index]+"_DIFF".toString(),1920,1080,1,comlayer.duration,30);
getcomp.openInViewer();
addVideofile(comlayer,getcomp);
addvideotwofile(vidlayer);
renderQ();
app.endUndoGroup();
}
function addVideofile(comlayer) {
app.project.activeItem.layers.add(comlayer);
}
function addvideotwofile(vidlayer){
var newlayer = app.project.activeItem.layers.add(vidlayer);
newlayer.blendingMode = BlendingMode.DIFFERENCE;
// var outputModule = item.outputModule()
}
function renderQ(){
var Qcomp =app.project.activeItem;
var Qitem = app.project.renderQueue.items.add(Qcomp);
}
You have an invisible Zero-Width Joiner between
buildUI(thisObj); ‍
and
function buildUI(thisObj) {
and again after
//myPanel.show();
const toHex = str => {
var result = '';
for (var i=0; i<str.length; i++) {
result += str.charCodeAt(i).toString(16);
}
return result;
};
const stringWithJoiner = ` ‍`; // space (20) and joiner (200D)
console.log(toHex(stringWithJoiner))
Here is your script without it
(function(thisObj) {
buildUI(thisObj);
function buildUI(thisObj) {
var windowName = "Diffrence Checker";
var myPanel = (thisObj instanceof Panel) ? thisObj : new Window("window", windowName, undefined, {
resizeable: true
});
// Dropdown list
var groupOne = myPanel.add("group", undefined, "groupOne");
groupOne.orientation = "row";
groupOne.add("StaticText", undefined, "Main Comp");
var mainDD = groupOne.add("dropdownlist", undefined, compArrayNames);
mainDD.size = [175, 25];
var groupTwo = myPanel.add("group", undefined, "groupTwo");
groupTwo.orientation = "row";
groupTwo.add("StaticText", undefined, "Diff File");
var diffDD = groupTwo.add("dropdownlist", undefined, VideoArrayNames);
diffDD.size = [175, 25];
// Button code
var createBT = myPanel.add("group", undefined, "createBT");
createBT.orientation = "column";
var mainbutton = createBT.add("button", undefined, "Create");
//myPanel.center();
//myPanel.show();
myPanel.onResizing = myPanel.onResize = function() {
this.layout.resize();
};
if (myPanel instanceof Window) {
myPanel.center();
myPanel.show();
} else {
myPanel.layout.layout(true);
myPanel.layout.resize();
}
}
// Write your helper functions here
var compArray = [];
var compArrayNames = [];
var VideoArray = [];
var VideoArrayNames = [];
for (var i = 1; i <= app.project.numItems; i++) {
if (app.project.item(i).hasVideo == true && app.project.item(i).file == null) {
compArray.push(app.project.item(i));
compArrayNames.push(app.project.item(i).name);
}
if (app.project.item(i).hasVideo == true && app.project.item(i).hasAudio == true) {
VideoArray.push(app.project.item(i));
VideoArrayNames.push(app.project.item(i).name);
}
}
function createCP() {
app.beginUndoGroup("Editing");
var comlayer = compArray[mainDD.selection.index];
var vidlayer = VideoArray[diffDD.selection.index];
var getcomp = app.project.items.addComp(VideoArrayNames[diffDD.selection.index] + "_DIFF".toString(), 1920, 1080, 1, comlayer.duration, 30);
getcomp.openInViewer();
addVideofile(comlayer, getcomp);
addvideotwofile(vidlayer);
renderQ();
app.endUndoGroup();
}
function addVideofile(comlayer) {
app.project.activeItem.layers.add(comlayer);
}
function addvideotwofile(vidlayer) {
var newlayer = app.project.activeItem.layers.add(vidlayer);
newlayer.blendingMode = BlendingMode.DIFFERENCE;
}
function renderQ() {
var Qcomp = app.project.activeItem;
var Qitem = app.project.renderQueue.items.add(Qcomp);
}
})
(this);

How to use setUserPointer/getUserPointer from Ammo.js

I want to print names of colliding objects. I made a very simple example.
I created an object to keep a user data:
const userData = { name: name };
I keep this object in a body using setUserPointer:
body.setUserPointer(userData);
I try to get this names using getUserPointer and print them. But I get "undefined" instead of names:
function detectCollison(): void
{
const dispatcher = physicsWorld.getDispatcher();
const numManifolds = dispatcher.getNumManifolds();
for (let i = 0; i < numManifolds; i++)
{
const contactManifold = dispatcher.getManifoldByIndexInternal(i);
const body0 = contactManifold.getBody0();
const body1 = contactManifold.getBody1();
const p0 = body0.getUserPointer();
const p1 = body1.getUserPointer();
console.log("first object: " + p0.name);
console.log("second object: " + p1.name);
}
}
Edited
This is pure TypeScript version. I tried to keep names as a body property but it does not work too. It prints "undefined" instead of names:
(this.body as any).name = name;
physicsWorld.addRigidBody(this.body);
function detectCollison(): void
{
const dispatcher = physicsWorld.getDispatcher();
const numManifolds = dispatcher.getNumManifolds();
for (let i = 0; i < numManifolds; i++)
{
const contactManifold = dispatcher.getManifoldByIndexInternal(i);
const body0 = contactManifold.getBody0();
const body1 = contactManifold.getBody1();
console.log("first object: " + (body0 as any).name);
console.log("second object: " + (body1 as any).name);
}
}
Solution:
const userData = { name: name };
(this.body as any).userData = userData;
function detectCollison(): void
{
const dispatcher = physicsWorld.getDispatcher();
const numManifolds = dispatcher.getNumManifolds();
for (let i = 0; i < numManifolds; i++)
{
const contactManifold = dispatcher.getManifoldByIndexInternal(i);
const body0 = contactManifold.getBody0();
const body1 = contactManifold.getBody1();
const rb0 = (Ammo as any).castObject( contactManifold.getBody0(), Ammo.btRigidBody );
const rb1 = (Ammo as any).castObject( contactManifold.getBody1(), Ammo.btRigidBody );
console.log("first object:", rb0.userData);
console.log("second object:", rb1.userData);
}
}

Very new to Javascript OOP: Passing a value to property through input fails to render single Element

I'm having problems rendering individual "li" elements through OOP approach.
I'm fetching the input from the user and using this info to create an item through a class. I'm then connecting this class to the list class responsible for rendering the list.
Once I fetch the value through a click event listener, the singleTaskRendering class isn't working. I wonder if I'm setting this up incorrectly?
const inputAccess = document.querySelector('.control').querySelector('input');
const addItemBtnAccess = document.getElementById('add-item-btn');
const toDoList = [];
const doneList = [];
//ads a li id to the item
const idGenerator = (array) => {
let n = 1;
let message = '';
for (let i = 0; i < array.length; i++) {
n += 1;
}
message = `li-${n}`;
return message;
}
class ItemTask {
constructor(itemValue, idGen) {
this.title = itemValue;
this.id = idGen;
}
}
const addItemBtnHandler = () => {
const toDoList = [];
const inputValue = inputAccess.value;
const item= new ItemTask(inputValue, idGenerator(toDoList));
toDoList.push(item);
return toDoList;
};
class singleTaskRendering {
constructor(product) {
this.product = product;
}
render() {
const titleElement = document.createElement('div');
titleElement.id = this.product.id;
titleElement.innerHTML = `
<li>
<h2>${this.product.title}</h2>
<button>Done</button>
<button>Delete</button>
</li>`;
titleElement.draggable = true;
}
}
class ItemLists {
constructor(listId, items) {
this.items = items;
this.listId = listId;
console.log(this.items, this.listId);
}
renderList() {
const renderHook = document.getElementById('hook');
const createList = document.createElement('lu');
createList.className = 'card';
createList.id = `${this.listId}-list`;
for(let item of this.items) {
const newItem = new singleTaskRendering(item);
console.log(newItem);
const itemEl = newItem.render();
console.log(itemEl, newItem);
createList.apppend(itemEl);
}
renderHook.append(createList);
}
}
const itemList = new ItemLists('active', toDoList);
itemList.renderList();
addItemBtnAccess.addEventListener('click', addItemBtnHandler);
The problem that you are having is that you call ItemLists on page load, which means it will only be processing an empty toDoList.
My solution is to rename renderList to appendItem.
Declare it at the top
Don't pass the list id and list to the constructor instead pass it to
appendItem in the clickhandler.
const inputAccess = document.querySelector('.control').querySelector('input');
const addItemBtnAccess = document.getElementById('add-item-btn');
const itemList = new ItemLists();
const toDoList = [];
const doneList = [];
//ads a li id to the item
const idGenerator = (array) => {
let n = 1;
let message = '';
for (let i = 0; i < array.length; i++) {
n += 1;
}
message = `li-${n}`;
return message;
}
class ItemTask {
constructor(itemValue, idGen) {
this.title = itemValue;
this.id = idGen;
}
}
const addItemBtnHandler = () => {
const toDoList = [];
const inputValue = inputAccess.value;
const item= new ItemTask(inputValue, idGenerator(toDoList));
itemList.appendItem('active', item);
};
class singleTaskRendering {
constructor(product) {
this.product = product;
}
render() {
const titleElement = document.createElement('div');
titleElement.id = this.product.id;
titleElement.innerHTML = `
<li>
<h2>${this.product.title}</h2>
<button>Done</button>
<button>Delete</button>
</li>`;
titleElement.draggable = true;
}
}
class ItemLists {
appendItem(listId, item) {
const renderHook = document.getElementById('hook');
const createList = document.createElement('lu');
createList.className = 'card';
createList.id = `${listId}-list`;
const newItem = new singleTaskRendering(item);
console.log(newItem);
const itemEl = newItem.render();
console.log(itemEl, newItem);
createList.apppend(itemEl);
renderHook.append(createList);
}
}
addItemBtnAccess.addEventListener('click', addItemBtnHandler);

Firebase Cloud Function isnt work in Prod. Getting error

I am getting the following error when going to the URL.
Error: could not handle the request
I can not seem to figure out why. What did I do wrong?
Here is my index.js file.
const functions = require('firebase-functions');
var request = require('request');
const admin = require('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest(async (req, res) => {
const itemDescription = req.query.itemDescription;
const pageNumber = req.query.pageNumber;
const categoryId = req.query.categoryId;
const sortBy = req.query.sortBy;
const narrowSearch = req.query.narrowSearch;
const typeOfListing = req.query.typeOfListing;
const sellerExclusions = req.query.sellerExclusions;
const tagsExclusions = req.query.tagsExclusions;
const country = req.query.country;
const minPrice = req.query.minPrice;
const maxPrice = req.query.maxPrice;
const entriesPerPage = req.query.entriesPerPage;
const buyingFormat = req.query.buyingFormat;
let operationName = "";
let entriesPerPage2 = "";
let sortOrder = "";
let currentPage = "";
if (pageNumber !== null) {
currentPage = pageNumber;
} else {
currentPage = 1;
}
if (typeOfListing === 'active') {
operationName = "findItemsAdvanced";
entriesPerPage2 = 50;
} else {
operationName = "findCompletedItems";
if (buyingFormat === "Auction") {
entriesPerPage2 = 50;
} else {
entriesPerPage2 = 25;
}
}
let apicall = "https://URL?";
if (typeOfListing === "active") {
if (sortBy !== null) {
apicall += "&sortOrder=";
apicall += sortBy;
sortOrder = sortBy;
} else {
apicall += "&sortOrder=";
apicall += "BestMatch";
sortOrder = "BestMatch";
}
} else {
if (sortBy !== null) {
apicall += "&sortOrder=";
apicall += sortBy;
sortOrder = sortBy;
} else {
apicall += "&sortOrder=";
apicall += "EndTimeSoonest";
sortOrder = "EndTimeSoonest";
}
}
if (categoryId !== null) {
apicall += "&categoryId=";
apicall += categoryId;
}
apicall += "&paginationInput.pageNumber=";
apicall += currentPage;
apicall += "&keywords=";
apicall += itemDescription;
apicall += "&paginationInput.entriesPerPage=" + entriesPerPage2;
apicall += "&itemFilter(0).name=SoldItemsOnly&itemFilter(0).value(0)=true";
request(apicall, function (error, response, body) {
if (!error && response.statusCode === 200) {
//here put what you want to do with the request
let paginationOutput = JSON.parse(body).findCompletedItemsResponse[0].paginationOutput;
let pageNumber = null;
let totalPages = null;
let totalEntries = null;
let totalInPage = null;
for (i = 0; i < paginationOutput.length; i++) {
pageNumber = paginationOutput[i].pageNumber[0];
totalPages = paginationOutput[i].totalPages[0];
totalEntries = paginationOutput[i].totalEntries[0];
totalInPage = paginationOutput[i].entriesPerPage[0];
}
let items = JSON.parse(body).findCompletedItemsResponse[0].searchResult[0].item;
let itemId = null;
let title = null;
let categoryId = null;
let categoryName = null;
let galleryURL = null;
let link = null;
let dateEnded = null;
let watchCount = null;
let bestOfferEnabled = null;
let listingType = null;
let soldForOriginal = null;
let timeLeft = null;
let dateLeft = null;
let bidCount = null;
let shipping = null;
//TODO
let soldForBestOffer = null;
var itemArray = {
result: []
};
for (i = 0; i < items.length; i++) {
itemId = items[i].itemId[0];
title = items[i].title[0];
galleryURL = items[i].galleryURL[0];
link = items[i].viewItemURL[0];
category = items[i].primaryCategory;
for (j = 0; j < category.length; j++) {
categoryName = category[j].categoryName[0];
categoryId = category[j].categoryId[0];
}
listingInfo = items[i].listingInfo;
for (k = 0; k < listingInfo.length; k++) {
watchCount = listingInfo[k].watchCount === undefined ? "0" : listingInfo[k].watchCount[0];
bestOfferEnabled = listingInfo[k].bestOfferEnabled[0];
listingType = listingInfo[k].listingType[0];
dateLeft = listingInfo[k].endTime[0];
}
sellingStatus = items[i].sellingStatus;
for (jj = 0; jj < sellingStatus.length; jj++) {
soldForOriginal = sellingStatus[jj].convertedCurrentPrice[0].__value__;
bidCount = sellingStatus[jj].bidCount === undefined ? "0" : sellingStatus[jj].bidCount[0];
timeLeft = sellingStatus[jj].timeLeft === undefined ? "-" : sellingStatus[jj].timeLeft[0];
}
shippingInfo = items[i].shippingInfo;
for (ii = 0; ii < shippingInfo.length; ii++) {
shipping = shippingInfo[ii].shippingServiceCost === undefined ? "0.0" : shippingInfo[ii].shippingServiceCost[0];
shippingType = shippingInfo[ii].shippingType[0];
if (shipping === "0.0") {
shipping = "0.00"
}
if (shippingType === 'Calculated') {
shipping = "TBD";
} else {
if (shipping === '0.00') {
shipping = "FREE";
}
}
}
itemArray.result.push({
"itemId": itemId,
"title": title,
"galleryURL": galleryURL,
"link": link,
"categoryName": categoryName,
"categoryId": categoryId,
"bidCount": bidCount,
"dateEnded": dateLeft,
"watchCount": watchCount,
"bestOfferEnabled": bestOfferEnabled,
"listingType": listingType,
"timeLeft": timeLeft,
"soldForOriginal": soldForOriginal
});
}
res.json({
ack: "success",
message: "results found",
currentPage: pageNumber,
totalPages: totalPages,
totalEntries: totalEntries,
totalInPage: totalInPage,
results: itemArray.result,
searchResult: JSON.parse(body).findCompletedItemsResponse[0].searchResult[0].item
});
} else {
res.json({
error: "didnt work"
});
}
})
});
In Cloud Functions you need to manage asynchronous method calls via Promises. request supports callback interfaces natively but does not return a promise.
You should use another library, like axios, along the following lines:
exports.addMessage = functions.https.onRequest(async (req, res) => {
try {
// ...
let apicall = "https://URL?";
// ...
apicall += "&itemFilter(0).name=SoldItemsOnly&itemFilter(0).value(0)=true";
const response = await axios.get(apicall);
// handle success
// ...
res.json({..});
} catch (error) {
res.status(500).send({ 'error': error });
}
});
Note that you probably need to be on the "Blaze" pricing plan.
As a matter of fact, the free "Spark" plan "allows outbound network requests only to Google-owned services". See https://firebase.google.com/pricing/ (hover your mouse on the question mark situated after the "Cloud Functions" title)
Also note that request is deprecated.

How could i get the result as trie format? object to string format from this code.

My expected output is ["Mark", "Mary", "Martod", "Mariam", "Marg"]
Getting output in console is ["Mark", "Mary", "Mart", "Mari", "Marg"]
How could I get the output as my expected result from this code? Can anyone do this for me?
function get_suggestion_array_from_object(searchstring, current_object) {
var suggestion_array = [];
suggestion_array.push(searchstring);
// console.log(suggestion_array);
append_object_key(suggestion_array, current_object);
}
var test_searchstring = 'Mar';
var test_current_object_string = '{"k":0,"y":0,"t":{"o":{"d":0}},"i":{"a":{"m":0}},"g":0}';
var test_current_object = JSON.parse(test_current_object_string);
console.log(test_current_object);
get_suggestion_array_from_object(test_searchstring, test_current_object);
function append_object_key(suggestion_array, current_object) {
var keys = Object.keys(current_object);
// CONCATENATE WITH SUGGESTION ARRAY ELEMENTS
var new_suggestion_array = [];
for (var i = 0; i < keys.length; i++) {
var current_key = keys[i];
var array_to_push = suggestion_array.slice();
for (var j = 0; j < suggestion_array.length; j++) {
array_to_push[j] = array_to_push[j] + current_key;
}
new_suggestion_array = new_suggestion_array.concat(array_to_push);
}
console.log(new_suggestion_array);
}
There are several approaches:
const get_suggestion_array_from_object = (searchstring, current_object_string) =>
current_object_string
.split(/[^a-z]+0[^a-z]+/)
.reduce((a, e) => e && a.concat(searchstring + e.replace(/[^a-z]+/g, '')) || a, [])
let searchstring = 'Mar';
let current_object_string = '{"k":0,"y":0,"t":{"o":{"d":0}},"i":{"a":{"m":0}},"g":0}';
console.log(get_suggestion_array_from_object(searchstring, current_object_string));
...
var test_searchstring = 'Mar';
var test_current_object_string = '{"k":0,"y":0,"t":{"o":{"d":0}},"i":{"a":{"m":0}},"g":0}';
var test_current_object = JSON.parse(test_current_object_string);
function get_suggestion_array_from_object(s, o) {
return Object.keys(o).map(function(k) {
var e = k;
var no = o[k];
while (no) {
var nk = Object.keys(no)[0];
e += nk;
no = no[nk];
}
return s + e;
})
}
console.log(get_suggestion_array_from_object(test_searchstring, test_current_object))

Categories

Resources