how to convert json to csv in react using map - javascript

I have convert the json data into csv on button click but what actually happen that they are storing in csv file in ,(comma) but I want them to be a separated in lines. How can I do that
Example = Minor,Minor But I Want them in separate Line.
Here is my code and Image.
This is csv file where minor minor and id in same line I want to separate them in other line
const apiForId = async() =>{
console.log("The value of isCheck", isCheck)
await axios.post(`${process.env.REACT_APP_API_UfL}/export/packs/`,isCheck
)
.then((res) => {
console.log(res)
setValue(res.data)
})
}
// Here download DataA
const downloadData = async(e) =>{
await apiForId()
down.current.click();
}
const data = value.map(item=>({
_id:item._id,
_id_sound:item.pack_sounds_ids.map(data=>data._id),
pack_name:item.pack_name,
chord_att_value:item.pack_sounds_ids.map(data=>data.chord_type_id.att_value),
instrumendts_att_value:item.pack_sounds_ids.map(data=>data.instruments_ids.map(ele => ele.att_value)),
key_att_value:item.pack_sounds_ids.map(item=>item.key_id.att_value),
maininstrument_att_value:item.pack_sounds_ids.map(item=>item.maininstrument_id.att_value),
product_att_value:item.pack_sounds_ids.map(item=>item.product_type_id.att_value),
refrence_att_value:item.pack_sounds_ids.map(item=>item.references_ids.map(ele=>ele.att_value)),
root_att_value:item.pack_sounds_ids.map(item=>item.root_note_id.att_value),
sound_bpm:item.pack_sounds_ids.map(item=>item.sound_bpm),
sound_index:item.pack_sounds_ids.map(item=>item.sound_index),
sound_name:item.pack_sounds_ids.map(item=>item.sound_name),
tags_att_value:item.pack_sounds_ids.map(item=>item.tags_ids.map(ele=>ele.att_value))
}))
const headers = [
{
label:"Pack ID",
key:"_id",
},
{
label:"Sound ID",
key:"_id_sound",
},
{
label:"Pack Name",
key:"pack_name",
},
{
label:"Chord",
key:"chord_att_value",
},
{
label:"Instruments",
key:"instrumendts_att_value",
},
{
label:"Key",
key:"key_att_value",
},
{
label:"Maininstrument",
key:"maininstrument_att_value",
},
{
label:"Product Type",
key:"product_att_value",
},
{
label:"Refrences",
key:"refrence_att_value",
},
{
label:"Root Note",
key:"root_att_value",
},
{
label:"BPM",
key:"sound_bpm",
},
{
label:"Index",
key:"sound_index",
},
{
label:"Name",
key:"sound_name",
},
{
label:"Tags",
key:"tags_att_value",
},
]
//BUTTON
<Button className="mx-5" onClick={downloadData}> Download CSV</Button>
<CSVLink headers={headers} data={data}><span ref={down}></span></CSVLink>

use this module https://www.npmjs.com/package/json2csv and using option unwind you can make it as 1 to many rows.
Details :
--unwind [paths]
Creates multiple rows from a single JSON document similar to MongoDB unwind.
--unwind-blank
When unwinding, blank out instead of repeating data. Defaults to false. (default: false)

Related

How to upload image and show preview in text editor using react?

i'm having a problem using draft-js text editor in react. My intention is to create a text editor where I can get the text to create a post, but I also need to get the image that you uploaded to the editor to place it as the cover of the post.
The following happens every time I load an image, it makes the request to the server. What I need is that the request is made once the user has submitted at the end of the creation of the post. So in this way I should not store images that the user regretted and then select another image.
frontend code:
export function EditorPost(props:any):JSX.Element{
let {postcontent, setpostcontent} = props;
const [content, setContent] = useState(EditorState.createWithContent(ContentState.createFromBlockArray(
convertFromHTML("<h2>hola nena</h2>")
)));
const onEditorStateChange = (editorState:any) => {
setContent(editorState); //UPDATE EDITOR STATE AND VALUE
setpostcontent({
...postcontent,
body:draftToHtml(convertToRaw(content.getCurrentContent())) //GET ONLY CONTENT OF THE FORM
});
console.log(postcontent);
}
function uploadImageCallBack(file:any):Promise<any> {
return new Promise(
async (resolve, reject) => {
const formdata = new FormData()
formdata.append('image', file)
try{
let resp = await axiosIntance.post('/upload', formdata);
resolve(resp)
}catch(err){
reject(err);
}
}
);
}
return (
<>
<Editor
editorState={content}
onEditorStateChange={onEditorStateChange}
toolbar={{
inline: { inDropdown: true },
list: { inDropdown: true },
textAlign: { inDropdown: true },
link: { inDropdown: true },
history: { inDropdown: true },
image: { uploadCallback: uploadImageCallBack, alt: { present: true, mandatory: true } },
}}
/>
</>
)
}
on the server i am using node and mysql. and create a model in the database for the posts, which contains the following columns: title, image (obtained from the text editor), body (html obtained from the text editor)

I'm getting duplicate firestore data array using DataTables plugin

I'm using the DataTable plugin, populating the table with data from Firebase Firestore database.
But I'm getting multiple data-set arrays
which continues till it reaches the length of data in the db.
Also, getting some errors
DataTables warning: table id=dataTable - Requested unknown parameter '5' for row 0, column 5. For more information about this error, please see http://datatables.net/tn/4
and
DataTables warning: table id=dataTable - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
But after I skip through all the errors, I get the Firestore data in the table.
Here is the code I'm using to get the data from Firestore and populating in the table;
$(document).ready(function () {
var dataSet = new Array();
var query = db.collection('news').orderBy('timestamp');
let observer = query.onSnapshot(snapshot => {
let changes = snapshot.docChanges();
changes.forEach(change => {
if (change.type == 'added') {
dataSet.push([change.doc.data().newsTitle,
change.doc.data().newsContent,
change.doc.data().newsImage,
change.doc.data().newsPublisher,
change.doc.data().timestamp.toDate()]);
console.log("data", dataSet);
const dataTable = $('#dataTable').DataTable({
data: dataSet,
order: [0, 'desc'],
columns: [
{ title: 'Title' },
{ title: 'Content' },
{ title: 'Picture' },
{ title: 'Publisher' },
{ title: 'Date' },
{ title: 'Action' }
]
});
dataTable.clear();
dataTable.rows.add(dataSet);
dataTable.draw();
}
})
});
})
What can I do to resolve this?
Figured it out, just removed the dataTable.rows.add(dataSet) from the loop.
$(document).ready(function () {
var dataSet = new Array();
var query = db.collection('news').orderBy('timestamp');
let observer = query.onSnapshot(snapshot => {
let changes = snapshot.docChanges();
changes.forEach(change => {
if (change.type == 'added') {
dataSet.push([change.doc.data().newsTitle,
change.doc.data().newsContent,
change.doc.data().newsImage,
change.doc.data().newsPublisher,
change.doc.data().timestamp.toDate()]);
}
})
console.log("data", dataSet);
const dataTable = $('#dataTable').DataTable({
data: dataSet,
order: [0, 'desc'],
columns: [
{ title: 'Title' },
{ title: 'Content' },
{ title: 'Picture' },
{ title: 'Publisher' },
{ title: 'Date' },
{ title: 'Action' }
]
});
dataTable.clear();
dataTable.rows.add(dataSet);
dataTable.draw();
});
})
But I'm still getting the alert error below twice, any ideas?
DataTables warning: table id=dataTable - Requested unknown parameter '5' for row 0, column 5. For more information about this error, please see http://datatables.net/tn/4

How to dynamically increment the limit on a collection cursor

I'm currently trying to implement a "Load more" button on a simple news page.
I've got the search working, thanks to Meteor Chef, and I followed the same principles to implement a "Load more" button. The relevant code is as follows:
Template:
Template.listAllNews.onCreated(function() {
template.limit = new ReactiveVar(10);
Tracker.autorun( () => {
template.subscribe( 'news.all', template.searchQuery.get(), template.limit.get(), () => {
setTimeout( () => {
template.searching.set( false );
}, 300 );
});
});
Template.listAllNews.events({
'click .load-more-button': function (event, template) {
var limit = template.limit.get();
limit += 10;
template.limit.set( limit );
}
});
Publication:
let query = {},
projection = { limit: limit, sort: { submitted: -1 } };
if ( search ) {
let regex = new RegExp( search, 'i' );
query = {
$or: [
{ title: regex }
]
};
projection.limit = 100;
}
return News.find( query, projection );
This works. The problem is: it refreshes all the data instead of just loading the extra 10 news articles. I want it to only load the extra 10 articles upon click, and not to "refresh" the subscription.
How can I do that?

Alternative way to fetch value from a local json file using $http

I want to load countries list from a countries json file stored locally. I have included the file in index.html as:
<!-- Including Json -->
<script src="json/countries.json"></script>
The Json file is saved in json folder with name countries.json, the file contents are as:
[
{
"country_id":"1",
"country_name":"Afghanistan"
},
{
"country_id":"2",
"country_name":"Albania"
},
{
"country_id":"3",
"country_name":"Algeria"
},
{
"country_id":"4",
"country_name":"American Samoa"
},
{
"country_id":"5",
"country_name":"Andorra"
},
{
"country_id":"6",
"country_name":"Angola"
},
{
"country_id":"7",
"country_name":"Anguilla"
},
{
"country_id":"8",
"country_name":"Antarctica"
},
{
"country_id":"9",
"country_name":"Antigua and Barbuda"
},
{
"country_id":"10",
"country_name":"Argentina"
},
{
"country_id":"11",
"country_name":"Armenia"
},
{
"country_id":"12",
"country_name":"Aruba"
},
{
"country_id":"13",
"country_name":"Australia"
},
{
"country_id":"14",
"country_name":"Austria"
},
{
"country_id":"15",
"country_name":"Azerbaijan"
},
{
"country_id":"16",
"country_name":"Bahamas"
},
{
"country_id":"17",
"country_name":"Bahrain"
},
{
"country_id":"18",
"country_name":"Bangladesh"
},
{
"country_id":"19",
"country_name":"Barbados"
},
{
"country_id":"20",
"country_name":"Belarus"
},
{
"country_id":"21",
"country_name":"Belgium"
},
{
"country_id":"22",
"country_name":"Belize"
},
{
"country_id":"23",
"country_name":"Benin"
},
{
"country_id":"24",
"country_name":"Bermuda"
}
]
To just name a few countries.
I could successfully parse the data and populate it to the UI from my controller referring the $htttp.get() service of angular as suggested by #jaime:
//Getting the base url inorder to tell app where to find countries json
var baseUrl = $location.absUrl().substring(0, $location.absUrl().indexOf('www'));
//Fetching the countries Json
return $http.get(baseUrl+'www/json/countries.json')
//On Fetching the countries lsit
.then( function(response){
$scope.countryList = response.data;
});
It works well, no doubt about it. But is there another alternative to achieve this functionality? Without using the $http.get()? I came accross angular.fromJson(), but it won't parse a file path as it requires it's argument to be a json object. Also I came across alternatives using jquery as in https://stackoverflow.com/a/12091134/1904479. is there any other alternative which doesn't require jquery, Instead uses angular or ionic code?
Actually, we can use it, by declaring it in a constants file as:
Step 1) Create a file constants.jsand add the json object into it:
var ConstantsCountries = [
{
"country_id":"1",
"country_name":"Afghanistan"
},
{
"country_id":"2",
"country_name":"Albania"
},
{
"country_id":"3",
"country_name":"Algeria"
},
{
"country_id":"4",
"country_name":"American Samoa"
},
{
"country_id":"5",
"country_name":"Andorra"
},
{
"country_id":"6",
"country_name":"Angola"
},
{
"country_id":"7",
"country_name":"Anguilla"
},
{
"country_id":"8",
"country_name":"Antarctica"
},
{
"country_id":"9",
"country_name":"Antigua and Barbuda"
},
{
"country_id":"10",
"country_name":"Argentina"
},
{
"country_id":"11",
"country_name":"Armenia"
},
{
"country_id":"12",
"country_name":"Aruba"
},
{
"country_id":"13",
"country_name":"Australia"
},
{
"country_id":"14",
"country_name":"Austria"
},
{
"country_id":"15",
"country_name":"Azerbaijan"
},
{
"country_id":"16",
"country_name":"Bahamas"
},
{
"country_id":"17",
"country_name":"Bahrain"
},
{
"country_id":"18",
"country_name":"Bangladesh"
},
{
"country_id":"19",
"country_name":"Barbados"
}
]
Step 2: Include the js file in the index.html as:
<!-----Constants Classes---->
<script src="Constants/Constants.js"></script>
Step 3: Use it in your controller as:
.controller('CountriesCtrl', function ($localStorage,$rootScope,$location,$ionicLoading,$ionicHistory,$timeout) {
$scope.countries = ConstantsCountries;
console.log(angular.toJson($scope.countries));
}))

jQuery ui autocomplete usin JSON file

I am having some trouble getting autocomplete to work specifically with a json file. It
giving following error whenever something is entered in the text box
url is undefined
following is my jQuery code
$(document).ready(function() {
$('#autocomplete').autocomplete({
minChars: 1,
source: function(request, response) {
var url='dataa.json';
$.getJSON(url,{term: request.term},function(data){
response($.map(data.ledgers, function(item) {
return item.value;
}));
})
}
});
});
and the JSON
{
"ledgers":
[
{
"id":"2001",
"name":"Bharat"
},
{
"id":"2003",
"name":"Gaurav"
},
{
"id":"2002",
"name":"Pankaj"
},
{
"id":"2022",
"name":"Purchase"
},
{
"id":"2007",
"name":"Ram"
},
{
"id":"2008",
"name":"Ramesh"
},
{
"id":"2009",
"name":"Suresh"
}
]}
Your JSON file format needs to contain value or label (or both). Change name to value and it should work fine.
$('#autocomplete').autocomplete({
minChars: 1,
source: function(request, response) {
var url='dataa.json';
$.getJSON(url,{term: request.term},function(data){
response($.map(data.ledgers, function (value, key) {
return {
label: value,
value: key
};
}));
})
}
});
Try adding 'use strict'; at the top of your $(document).ready(). That may point out what the problem is...
return item.value;
item does not have a value, try returning id or name, which it does have.

Categories

Resources