Associative array dynamic key addition error - javascript

I am converting a CSV to JSON object to render data in a html table. When creating object I am using associative array to create a key,value pair structure of the object, but last column of the CSV file is becoming inaccessible because it is creating object as follows,
Object {code:"F1",description:"Family 1",discount: "0.2","validity":"1434567098"}
So I can't access data for "validity" in my code. It is only happening with the last column of CSV file. Please help me to resolve this issue.
Please refer to this block of code,
reader.onload = function(e) {
var fileData = e.target.result.split("\n"),
tableData = [],
tData = {},
length = fileData.length;
for(i=0;i<length;i++){
csvObj.push(fileData[i]);
}
theaderArray = csvObj[0].toLowerCase().split(",");
for(k=1;k<csvObj.length;k++){
tData = {};
csvDataArray = csvObj[k].split(",");
if(csvDataArray[0]){
angular.forEach(theaderArray, function(val,key){
tData[val] = csvDataArray[key];
});
}
tableData.push(tData);
}
$rootScope.familyList = tableData;
}

Related

Loop through Object of Sheets JavaScript

I'm using import * as XLSX from 'xlsx' and I'm trying to loop through an Object containing excel sheets. Everything was fine and dandy when I had one spreadsheet since I could easily access the length. My specifications changed and I need to be able to send to a DB only specific worksheets the user selects from the excel file. I don't know much about JavaScript but for some reason, I had to parse the data after stringifying it to be able to recognize the headers from the excel file. This is some of the code I have:
if (this.selectedDepartment.includes("CSET")) {
var sheet_name = workbook.SheetNames[4];
var worksheet = workbook.Sheets[sheet_name];
var classData = XLSX.utils.sheet_to_json(worksheet, { raw: true });
XLSX.utils.book_append_sheet(newWorkbook, classData, "CSET");
}
if (this.selectedDepartment.includes("COMM")) {
sheet_name = workbook.SheetNames[5];
var worksheet = workbook.Sheets[sheet_name];
classData = XLSX.utils.sheet_to_json(worksheet, { raw: true });
XLSX.utils.book_append_sheet(newWorkbook, classData, "COMM");
}
var classData_JSON = JSON.stringify(newWorkbook);
var json = JSON.parse(classData_JSON);
Below, trying to store into my array:
for (var i = 0; i < json.length; i++)
{
var _courseID = json[i].Subject + " " + this.courseID[i];
this._newClasses[i] = {
'CRN': json[i].CRN, 'Subject': json[i].Subject, 'CourseID': _courseID, 'Section': json[i].Section, 'UserID': json[i].UserID, 'Max': json[i].Max,
'CourseComments': json[i]["Course Comments"], 'Monday': this.Monday[i], 'Tuesday': this.Tuesday[i], 'Wednesday': this.Wednesday[i], 'Thursday': this.Thursday[i]
// more code
this.classService.Put_Classs(this._newClasses[i]).then(classData => classData.subscribe());
My problem if you look in the picture is I can't find a way to loop through one sheet at a time, get the sheet name during runtime, and then loop through that sheet and store into my array before moving on to the next one. COMM and CSET both have the length property but I'm not sure how to access this.

Remove rows having blank value for some column from CSV file using Node JS

I have a CSV file where for a row some value is missing. So if a value is missing then we need to delete that row from the CSV file. I am facing a problem with doing that. Please help me with this.
We can use a CSV parsing library, such as the excellent Papa Parse to parse the data, then we can filter the rows based on the column that we wish to filter on.
For example:
const Papa = require('papaparse');
let csvData = `Col1,Col2,Col3\na1,b1,c1\na2,,c2\na3,b3,c3`;
let { data } = Papa.parse(csvData, { header: true });
console.log("Original csv data:");
console.log(csvData);
function filterEmptyValues(data, column) {
return data.filter(row => row[column]);
}
let filteredData = filterEmptyValues(data, "Col2");
let filteredCsv = Papa.unparse(filteredData);
console.log("\nFiltered csv:")
console.log(filteredCsv);

ReactJS - How to skip empty rows in excel while reading with xlsx

I'm successfully reading my Excel file in React by following this SO thread as.
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
let readedData = XLSX.read(data, {type: 'binary'});
const wsname = readedData.SheetNames[0];
const ws = readedData.Sheets[wsname];
/* Converts a worksheet object to an array of JSON objects*/
const parsedData = XLSX.utils.sheet_to_json(ws, {header:1});
console.log(parsedData);
}
reader.readAsBinaryString(fileName)
But having a simple problem, i.e., it's reading empty rows as well and causing empty entries in array.
Output of console.log(parsedData); in the above code is
I know a quick hack is to remove empty entries from the array but I want to know a better approach to avoid this problem even happening.
Edit - It's "blankrows" and not "blankRows"
I did a search and came across a similar question on gitmemory here, which shows that there's a blankRows property you can set to false in order to skip blank rows, which would look like this with your implementation:
/* Converts a worksheet object to an array of JSON objects*/
const parsedData = XLSX.utils.sheet_to_json(ws, {
header:1,
blankrows: false
});

Filter data from bulk csv to small csv

I have one raw sheet and that needs to be divided into certain templates.From the raw sheet(raw_data), I have one more sheet (man_data) in which whole data is present.I need to check the manufacturer(column E from raw_data) to be checked with (column C from man_data). If data is not present in the man_data then i need that data to be written in new template(manufacturer_template in column C(name)).
Please find below the template format of the sheet.
How can we write a program in a simple javascript code.I am very new at this and learning javascript now so kindly help me out in writing the code.
Thanks.
Kindly let me know if you need any help regarding question description.
Please find attached files on below onedrive link.
https://1drv.ms/f/s!Asot5b-vLh9Qhlvu9HuMtlKMSmdV
You can read data using javascript.
then apply filter method of javascript to get filtered result...
var data = [1,2,3,4,5];
data.filter(function(obj){ return obj>2 })
Likewise above code return numbers greater than 2
You can write any logic in '{ }' of function
HTML Code to accept csv file:
<input type="file" id="cvsFileChooser" accept=".csv" />
JavaScript code for reading and processing csv file
$('#cvsFileChooser').change(function() {
var output = "";
var csvInputFilesName = $('#cvsFileChooser').prop("files");
var file = csvInputFilesName[0];
var reader = new FileReader();
reader.onload = function(e) {
output = e.target.result;
displayContents(output);
};
reader.readAsText(file);
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
}
});
function displayContents(txt) {
var rows = txt.split('\n')// this will give each row array saperate from csv data
for(i=0;i<row.length;i++){ // iteration upto the end of all rows
var singleRow = rows[i]; // get each row
var columnArray = singleRow.split(','); // get column array data for each row
if(columnArray[ your excel column number to check data ] !="")
{
// your logic to copy data in new array
}
}
}

Firebase - Data structure issue for extracting an object from nested structure

Firebase - Data structure issue for extracting an object from nested structure.
I want to find the uid and then check if the key is a jobId.
I've labelled accordingly below.
I'm using typescript and angular2 with firebase.
This is my current attempt that returns "null":
var jobId = "-K5fIAiuHM-4xeEQJiIS";
var uid = "3f61ae7a-99a1-4cbf-9c8e-00b2249956a7";
var userRef = this.refApp.child('key').child(uid);
var query = userRef.child('jobId').child(jobId);
query.on('value', (snap) => {
//This returns null
var response = snap.val();
});
This is my database structure:
Your structure is /applications/$userId/$jobId. Use those keys to get to your data.
JSBin Demo
var jobId = "-K5fIAiuHM-4xeEQJiIS";
var uid = "3f61ae7a-99a1-4cbf-9c8e-00b2249956a7";
var refApp = new Firebase('<my-firebase-app>/applications');
var jobRef = refApp.child(uid).child(jobId);
jobRef.on('value', (snap) => console.log(snap.val()));
Right now you're using "key", which I believe is from my previous demo. That's just for show, not for your actual solution. Keep your data structure in mind when reading the sample code, because it can vary.

Categories

Resources