Uncaught ReferenceError: test is not defined, calling onclick in codepen - javascript

What i want to achieve is to call generateDocx and generatePDF with two separate buttons, trying it some versions ago didn't give me any problems so i am a bit dumbfounded.
I tried to use
onclick
event listener
dummy function to see if maybe the position was the problem
I have this up on codepen, so it could be the website per se that gives me the problem, at this point i am really clueless
Codepen link
EDIT: if i remove "import * as converter from "https://cdn.skypack.dev/docx-pdf#0.0.1";" at least id downloads the docx
const { AlignmentType, Document, HeadingLevel, Packer, Paragraph, TabStopPosition, TabStopType, TextRun } = docx;
import * as converter from "https://cdn.skypack.dev/docx-pdf#0.0.1";
import * as underscore from "https://cdn.skypack.dev/underscore#1.13.6";
const test = {
id: "1",
informazioniBase: {
nome: "Lorenzo",
cognome: "Dombo",
label: "???",
img: "",
email: "lorenzoemail#l.com",
telefono: "+3932731444",
url: "https://urlpersonale.com",
riassunto: "Riassunto candidato",
luogo: {
indirizzo: "Via Criso laso 12",
codicePostale: "00133",
citta: "Roma",
provincia: "Roma",
codicePaese: "IT",
regione: "Lazio"
},
social: [{
network: "Twitter",
username: "user",
url: "https://twitter.com/user"
}]
},
lavoro: [{
attivo: true,
nomeAzienda: "Majormajor",
posizioneLavorativa: "Programmatore",
url: "https://azienda.com",
dataInizio: "11/12/2010",
dataFine: "dataDiFine",
descrizione: "Questa è una prova, utilizza dei doppi a capo come segnale per andare a capo, poiché tramite un JSON è difficile capire quando andare, però sono sicuro di poter automatizzare questo compito facilmente, QUESTO PROBLEMA E' STATO RISOLTO MA TENGO IL TESTO PER LA SUA LUNGHEZZA",
Riassunto: "riassunto"
}],
educazione: [{
attivo: false,
luogo: "università",
url: "https://università.com/",
area: "Informatica",
TipoLaurea: "Magistrale",
dataInizio: "9/10/2019",
dataFine: "9/10/2024",
voto: "110",
note: "Questa è una prova, utilizza degli a capo come segnale per \nappunto andare a capo, poiché tramite un JSON è difficile capire \nnquando andare, però sono sicuro di poter automatizzare \nquesto compito facilmente, QUESTO PROBLEMA E' STATO RISOLTO MA TENGO IL TESTO PER LA SUA LUNGHEZZA"
}],
certificati: [
{
certificante: "certificante",
certificato: "nome Certificato"
},
{
certificante: "certificante2",
certificato: "nome Certificato2"
}
],
skills: ["Angular", "Java", "Javascript?", "HTML"],
lingue: [
{
lingua: "Inglese",
livello: "C1",
},
{
lingua: "Italiano",
livello: "Madrelingua",
}
],
progetti: [{
nome: "progetto",
descrizione: "Questa è una prova, utilizza degli a capo come segnale per \nappunto andare a capo, poiché tramite un JSON è difficile capire \nnquando andare, però sono sicuro di poter automatizzare \nquesto compito facilmente, QUESTO PROBLEMA E' STATO RISOLTO MA TENGO IL TESTO PER LA SUA LUNGHEZZA",
riassunto: "riassunto",
paroleChiave: [
"HTML",
"CSS",
"JavaScript"
],
dataInizio: "data inizio",
dataFine: "data fine",
url: "https://progetto.com/",
ruolo: "ruolo",
tipo: "applicazione / sviluppo"
}]
};
class DocumentCreator {
create([lavoro, educazione, skills, certificati, lingue, progetti]) {
const document = new Document({
sections: [{
children: [
new Paragraph({
text: `${test.informazioniBase.nome} ${test.informazioniBase.cognome}`,
heading: HeadingLevel.TITLE,
}),
this.createContactInfo(test.informazioniBase.telefono, test.informazioniBase.url, test.informazioniBase.email, test.informazioniBase.luogo),
this.createHeading("Educazione"),
...educazione
.map((educazioneSingola) => {
const arr = [];
arr.push(
this.createInstitutionHeader(educazioneSingola.luogo,
this.createPositionDateText(educazioneSingola.dataInizio, educazioneSingola.dataFine, educazioneSingola.attivo)
),
);
arr.push(this.createRoleText(`${educazioneSingola.TipoLaurea} - ${educazioneSingola.voto}`));
arr.push(new Paragraph({ text: educazioneSingola.note }))
return arr;
})
.reduce((prev, curr) => prev.concat(curr), []),
this.createHeading("Esperienze Lavorative"),
...lavoro
.map((lavoroSingolo) => {
const arr = [];
arr.push(
this.createInstitutionHeader(
lavoroSingolo.nomeAzienda,
this.createPositionDateText(lavoroSingolo.dataInizio, lavoroSingolo.dataFine, lavoroSingolo.attivo),
),
);
arr.push(this.createRoleText(lavoroSingolo.posizioneLavorativa));
arr.push(new Paragraph({ text: lavoroSingolo.descrizione }))
return arr;
})
.reduce((prev, curr) => prev.concat(curr), []),
this.createHeading("Progetti"),
...progetti
.map((progettoSingolo) => {
const arr = [];
arr.push(
this.createInstitutionHeaderNoDate(progettoSingolo.nome),
);
arr.push(this.createRoleText(`${progettoSingolo.ruolo} - ${progettoSingolo.tipo}`));
const bulletPoints = this.splitParagraphIntoBullets(progettoSingolo.descrizione);
bulletPoints.forEach((bulletPoint) => {
arr.push(this.createBullet(bulletPoint));
});
arr.push(
this.createRoleTextUnderlined("Tecnologie Utilizzate")
);
arr.push(this.createSkillList(progettoSingolo.paroleChiave))
return arr;
})
.reduce((prev, curr) => prev.concat(curr), []),
this.createHeading("Skills,Certificati e Lingue"),
this.createSubHeading("Skills"),
this.createSkillList(skills),
this.createSubHeading("Certificati"),
...this.createAchivementsList(certificati),
this.createSubHeading("Lingue"),
...this.createLanguageList(lingue)
],
}],
});
return document;
}
createContactInfo(numerotelefono, url, email, luogo) {
return new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new TextRun(`Telefono: ${numerotelefono} | LinkedIn: ${url} | Email: ${email}`),
new TextRun({
text: `${luogo.indirizzo}, ${luogo.citta}`,
break: 1,
}),
],
});
}
createHeading(text) {
return new Paragraph({
text: text,
heading: HeadingLevel.HEADING_1,
thematicBreak: true,
break: 1
});
}
createSubHeading(text) {
return new Paragraph({
text: text,
heading: HeadingLevel.HEADING_2,
break: 2
});
}
createInstitutionHeader(institutionName, dateText) {
return new Paragraph({
tabStops: [
{
type: TabStopType.RIGHT,
position: TabStopPosition.MAX,
},
],
children: [
new TextRun({
text: institutionName,
bold: true,
}),
new TextRun({
text: `\t${dateText}`,
bold: true,
}),
],
});
}
createInstitutionHeaderNoDate(institutionName) {
return new Paragraph({
tabStops: [
{
type: TabStopType.RIGHT,
position: TabStopPosition.MAX
},
],
children: [
new TextRun(
{
text: institutionName,
bold: true
}
),
],
});
}
createRoleText(roleText) {
return new Paragraph({
children: [
new TextRun({
text: roleText,
italics: true,
}),
],
});
}
createRoleTextUnderlined(roleText) {
return new Paragraph({
children: [
new TextRun({
text: roleText,
underline: {}
}),
],
});
}
createBullet(text) {
return new Paragraph({
text: text,
bullet: {
level: 0,
},
});
}
// tslint:disable-next-line:no-any
createSkillList(skills) {
return new Paragraph({
children: [new TextRun(skills.map((skill) => skill).join(", ") + ".")],
});
}
// tslint:disable-next-line:no-any
createAchivementsList(certificati) {
return certificati.map(
(certificato) =>
new Paragraph({
text: `${certificato.certificante} - ${certificato.certificato}`,
bullet: {
level: 0,
},
}),
);
}
// tslint:disable-next-line:no-any
createLanguageList(lingue) {
return lingue.map(
(lingua) =>
new Paragraph({
text: `${lingua.lingua} - ${lingua.livello}`,
bullet: {
level: 0,
},
}),
);
}
createInterests(interests) {
return new Paragraph({
children: [new TextRun(interests)],
});
}
splitParagraphIntoBullets(text) {
console.log(text)
return text.split("\n\n");
}
// tslint:disable-next-line:no-any
createPositionDateText(dataInizio, dataFine, attivo) {
const dataFineTesto = attivo ? "Attuale" : dataFine;
console.log(`${dataInizio} - ${dataFineTesto}`)
return `${dataInizio} - ${dataFineTesto}`;
}
};
function generateDocx() {
console.log("etra")
const documentCreator = new DocumentCreator();
const doc = documentCreator.create([test.lavoro, test.educazione, test.skills, test.certificati, test.lingue, test.progetti]);
docx.Packer.toBlob(doc).then((blob) => {
console.log(blob);
saveAs(blob, `${test.informazioniBase.nome} ${test.informazioniBase.cognome}.docx`);
console.log("Document created successfully");
});
};
function generatePDF() {
const doc = this.create([this.test.lavoro, this.test.educazione, this.test.skills, this.test.certificati, this.test.lingue, this.test.progetti]);
converter(doc, 'output.pdf', function (err, result) {
if (err) {
console.log("Converting Doc to PDF failed", err);
}
console.log("Converting Doc to PDF succesfull", result);
});
};
<h1>Tasto genera WORD</h1>
<button type="button" onclick="generateDocx()">GENERA</button>
<button type="button" onclick="test()">GENERA PDF</button>

Related

Javascript - check if certain values are in an array of objects

Say I have an array of 5 objects, each with 2 keys (eg, 'title' & 'author').
I want to check the truthiness that 3 SPECIFIC titles exist in the array.
What's the best way to do that?
I have the following... but it doesn't seem very efficient:
const books = [
{ title: 'Book1', author: 'Author1' },
{ title: 'Book2', author: 'Author2' },
{ title: 'Book3', author: 'Author3' },
{ title: 'Book4', author: 'Author4' },
{ title: 'Book5', author: 'Author5' },
];
const certainBooks = books.some((b) => b.title === 'Book2')
&& books.some((b) => b.title === 'Book3')
&& books.some((b) => b.title === 'Book5')
if (certainBooks) {
// Do stuff
}
If the values and number of titles is dynamic, it might be worth creating an index of titles in the array; something with O(1) time complexity for faster lookups
const books = [
{ title: 'Book1', author: 'Author1' },
{ title: 'Book2', author: 'Author2' },
{ title: 'Book3', author: 'Author3' },
{ title: 'Book4', author: 'Author4' },
{ title: 'Book5', author: 'Author5' },
];
const titleIndex = new Set(books.map(({ title }) => title));
const titlesExist = (...titles) =>
titles.every(title => titleIndex.has(title))
console.log("Book2, Book3, Book5:", titlesExist("Book2", "Book3", "Book5"));
console.log("Book1:", titlesExist("Book1"));
console.log("Book5, Book6:", titlesExist("Book5", "Book6"));
A more general approach would be to map the books to their titles, then check that .every one of the titles you're looking for exists.
const books = [
{ title: 'Book1', author: 'Author1' },
{ title: 'Book2', author: 'Author2' },
{ title: 'Book3', author: 'Author3' },
{ title: 'Book4', author: 'Author4' },
{ title: 'Book5', author: 'Author5' },
];
const titles = books.map(({ title }) => title);
const toFind = ['Book2', 'Book3', 'Book5'];
if (toFind.every(title => titles.includes(title))) {
console.log('do stuff');
}
If the array of books is large, you could benefit by making titles a Set instead of an array - Set#has is faster than Array#includes when there are a lot of elements.
You could loop over them
const books = [
{ title: "Book1", author: "Author1" },
{ title: "Book2", author: "Author2" },
{ title: "Book3", author: "Author3" },
{ title: "Book4", author: "Author4" },
{ title: "Book5", author: "Author5" },
];
const booksNeeded = ["Book2", "Book3", "Book4"];
for (let book of books) {
const lookForIndex = booksNeeded.findIndex(
(title) => title.toLowerCase() === book.title.toLowerCase()
);
if (lookForIndex !== -1) {
booksNeeded.splice(lookForIndex, 1);
}
if (!booksNeeded.length) {
break; // Early break if all the books has been found
}
}
if (!booksNeeded.length) {
console.log("Do Something");
} else {
console.log("Something else");
}
const books = [
{ title: 'Book1', author: 'Author1' },
{ title: 'Book2', author: 'Author2' },
{ title: 'Book3', author: 'Author3' },
{ title: 'Book4', author: 'Author4' },
{ title: 'Book5', author: 'Author5' },
];
let ops = 0;
let search = [ "Book2", "Book3", "Book4" ];
let { length } = search;
for ( let i = 0, len = books.length; length && i < len; i++ ){
ops++;
if ( search.includes(books[i].title) ){
length--;
}
}
if ( !length ){
console.log("All books found!");
} else {
console.log("Not all books found!")
}
console.log( "Number of operations: ", ops );

how to format an object of array to a new one

I'm trying to transform an object contain array to another one with javascript. Below is an example of the object field and what the formatted one should look like.
The data after formating must show me only fileds who has the "ABS" in funcName
let beforeData = {
SUMMER: [
{ funcName: '{{WORKING_ABS}}', subject: { en: "Exercice1"} },
{ funcName: '{{PULLS_BODY}}', subject: { en: "Exercice2"} },
],
WINTER: [
{ funcName: '{{FULL_BODY}}', subject: { en: "Exercice3"} },
{ funcName: '{{REST_ABS}}', subject: { en: "Exercice4"} },
]
};
I need The object to be exactly like this one
let AfterData ={
worklinks: [
{
name: 'Exercice1',
link: '{{WORKING_ABS}}',
},
{
name: 'Exercice4',
link: '{{REST_ABS}}',
},
]
},
I was trying to make a method like this one (Its just a draft ) , maybe somone will help to improve this method
export const functTransform = (dataaas) => { Object.keys(dataaas).map(fiels => ({
worklinks =>funcName.search("ABS") > -1).map(({funcName, subject}) => ({
link: funcName,
name: subject.en
}))};
I'm new working with javascript so any help is greatly appreciated, Thanks.
Consider following code:
const beforeData = {
SUMMER: [
{ funcName: '{{WORKING_ABS}}', subject: { en: "Exercice1"} },
{ funcName: '{{PULLS_BODY}}', subject: { en: "Exercice2"} },
],
WINTER: [
{ funcName: '{{FULL_BODY}}', subject: { en: "Exercice3"} },
{ funcName: '{{REST_ABS}}', subject: { en: "Exercice4"} },
]
};
const isABS = (str) => str.indexOf('ABS') > -1;
const result = Object.values(beforeData).flat().map(o => ({link: o.funcName, name: o.subject.en})).filter(o => isABS(o.link));
console.log(result);
You could do it like this? (Reduce with forEach)
let beforeData = {
SUMMER: [
{ funcName: '{{WORKING_ABS}}', subject: { en: "Exercice1"} },
{ funcName: '{{PULLS_BODY}}', subject: { en: "Exercice2"} },
],
WINTER: [
{ funcName: '{{FULL_BODY}}', subject: { en: "Exercice3"} },
{ funcName: '{{REST_ABS}}', subject: { en: "Exercice4"} },
]
};
function transform(inputData, funcComparator){
if (funcComparator == undefined){
funcComparator = (item) => item.funcName.includes("ABS");
}
return Object.values(inputData).reduce((aggArr, arr) => {
arr.forEach(item => {
if (funcComparator(item)){
const itemCopy = {name: item.subject.en, link: item.funcName};
aggArr.push(itemCopy);
}
})
return aggArr;
}, []);
}
//use it to find all your "ABS":
console.log(transform(beforeData));
//another example, use it to find all your "BODY":
//console.log(transform(beforeData, (item) => item.funcName.includes("BODY")));
Output:
[
{
"name": "Exercice1",
"link": "{{WORKING_ABS}}"
},
{
"name": "Exercice4",
"link": "{{REST_ABS}}"
}
]

How to edit an Embed Author?

I want to edit the author of an embed sent by my bot.
The message is sent by this code :
task_chan.send('', {
embed: {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
})
To edit the message I've tried :
taken.embeds[0].author.icon_url = util.avatarURL
taken.embeds[0].author.name = util.username
taken.edit(new Discord.RichEmbed(taken.embeds[0]));
taken contain the message to edit and util an user.
And it only change the name…
I don't understand why but author.icon_url is undefined between these two code samples.
I hope you can help me :)
method channel.send return a promise, so you can use .then(msg=> to get a message object.
let testEmbed = {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
}
task_chan.send({embed:testEmbed}).then(msg => {
testEmbed.name = 'LOL'
testEmbed.iconURL = 'SOMEURL'
msg.edit({embed:testEmbed})
})
I would recommend that you use the built-in methods for creating embeds, in my opinion it is more convenient.

Creating new data object set from multiple nested arrays

I've have a complex data structure with multiple nested arrays in place.
Below is the current structure
var contentData = {
data: {
content: [
{
type: "column",
sections: [
{
sub: [
{
type: "heading-1",
text: "Heading Text"
}
]
}
]
},
{
type: "acc-item",
sections: [
{
sub: [
{
type: "heading-1",
text: "Heading Text"
},
{
type: "ordered-item",
text: "Item 1"
},
{
type: "unordered-item",
text: "Item 2"
}
]
}
]
},
{
type: "acc-item",
sections: [
{
sub: [
{
type: "heading-1",
text: "Heading Text 2"
}
]
}
]
}
]
}
}
So What I wanted is,
I wanted to group all the ordered-item & unordered-item into a new object like {type: 'list', items:[all list items]}.
I need to extract all items which are inside sub and push it to new object embedded and it should placed in the root level like below,
{type:"acc-item",embedded:[{type:"heading-1",text:"Heading Text 2"}]};
So What I've done so far,
I can able to group acc-item, but not the ordered-item & unordered-item.
So my final expected result should like this,
[{
"type": "column",
"embedded": [
{
"type": "heading-1",
"text": "Heading Text"
}
]
},
{
"type": "acc-group",
"items": [
{
"type": "acc-item",
"embedded": [
{
"type": "heading-1",
"text": "Heading Text"
},
{
"type": "list",
"items": [
{
"type": "ordered-item",
"text": "Item 1"
},
{
"type": "unordered-item",
"text": "Item 2"
}
]
}
]
},
{
"type": "acc-item",
"embedded": [
{
"type": "heading-1",
"text": "Heading Text 2"
}
]
}
]
}]
Below is my code,
var group,contentData={data:{content:[{type:"column",sections:[{sub:[{type:"heading-1",text:"Heading Text"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text"},{type:"ordered-item",text:"Item 1"},{type:"unordered-item",text:"Item 2"}]}]},{type:"acc-item",sections:[{sub:[{type:"heading-1",text:"Heading Text 2"}]}]}]}},types=[["list",["ordered-item","unordered-item"]],["accordion",["acc-item"]]];
var result = contentData.data.content.reduce((r, o) => {
var type = (types.find(({ 1: values }) => values.indexOf(o.type) > -1)|| {})[0];
if (!type) {
r.push(o);
group = undefined;
return r;
}
if (!group || group.type !== type) {
group = { type, items: [] };
r.push(group);
}
group.items.push(o);
return r;
}, []);
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, ' ') + '</pre>';
You could store the last items array as well as the last embedded array and use them until a column type is found.
var contentData = { data: { content: [{ type: "column", sections: [{ sub: [{ type: "heading-1", text: "Heading Text" }] }] }, { type: "acc-item", sections: [{ sub: [{ type: "heading-1", text: "Heading Text" }, { type: "ordered-item", text: "Item 1" }, { type: "unordered-item", text: "Item 2" }] }] }, { type: "acc-item", sections: [{ sub: [{ type: "heading-1", text: "Heading Text 2" }] }] }] } },
list = ["ordered-item", "unordered-item"],
lastItems, lastEmbedded,
result = contentData.data.content.reduce((r, { type, sections }) => {
if (type === 'column') {
r.push({ type, embedded: sections.reduce((q, { sub }) => q.concat(sub), []) });
lastItems = undefined;
lastEmbedded = undefined;
return r;
}
if (!lastItems) r.push({ type: "acc-group", items: lastItems = [] });
lastItems.push(...sections.map(({ sub }) => ({
type,
embedded: sub.reduce((q, o) => {
if (list.includes(o.type)) {
if (!lastEmbedded) q.push({ type: 'list', items: lastEmbedded = [] });
lastEmbedded.push(o);
} else {
q.push(o);
lastEmbedded = undefined;
}
return q;
}, [])
})));
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The Array.prototype and Object.prototype methods are perfect for this kind of thing.
And you're right that this is some complicated kind of logic.
I would suggest that you definitely need some unit tests for this, and try break in to separate pieces.
Here's how I'm thinking I'd do it.
1. Group By the type to create your groups..
I'm actually creating a more generic solution that you've asked for here. That is, I'm not just grouping the 'acc-item', but everything.
I did a quick search for 'array group by javascript' and it gives us this answer which suggests using Array.reduce, so let's do that.
const groupedData = contentData.data.content.reduce((acc, cur) => {
//Check if this indexed array already exists, if not create it.
const currentArray = (acc[`${cur.type}-group`] && acc[`${cur.type}-group`].items) || [];
return {
...acc,
[`${cur.type}-group`]: {
type: `${cur.type}-group`,
items: [...currentArray, cur]
}
}
}, {});
2. Now for each of those items, we need to look at their subs, and group just the list items.
To do this, we basically want to find all the `item -> sections -> sub -> types and filter them into two arrays. A quick google on how to create two arrays using a filter gives me this answer.
First though, we need to flatten that sections-> subs thing, so lets just do that.
function flattenSectionsAndSubs(item) {
return {
type: item.type,
subs: item.sections.reduce((acc, cur) => ([...acc, ...cur.sub]), [])
};
}
And I'll just copy paste that partition function in:
function partition(array, isValid) {
return array.reduce(([pass, fail], elem) => {
return isValid(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]];
}, [[], []]);
}
const listTypes = ['ordered-item', 'unordered-item'];
function createEmbeddedFromItem(item) {
const [lists, nonLists] = partition(item.subs, (v) => listTypes.includes(v.type);
return {
type: item.type,
embedded: [
...nonLists,
{
type: "list",
items: lists
}
]
}
}
Putting this all together and we get.
const contentData = {
data: {
content: [{
type: "column",
sections: [{
sub: [{
type: "heading-1",
text: "Heading Text"
}]
}]
},
{
type: "acc-item",
sections: [{
sub: [{
type: "heading-1",
text: "Heading Text"
},
{
type: "ordered-item",
text: "Item 1"
},
{
type: "unordered-item",
text: "Item 2"
}
]
}]
},
{
type: "acc-item",
sections: [{
sub: [{
type: "heading-1",
text: "Heading Text 2"
}]
}]
}
]
}
}
function partition(array, isValid) {
return array.reduce(([pass, fail], elem) => {
return isValid(elem) ? [
[...pass, elem], fail
] : [pass, [...fail, elem]];
}, [
[],
[]
]);
}
function flattenSectionsAndSubs(item) {
return {
type: item.type,
subs: item.sections.reduce((acc, cur) => ([...acc, ...cur.sub]), [])
};
}
const listTypes = ['ordered-item', 'unordered-item'];
function createEmbeddedFromItem(item) {
const [lists, nonLists] = partition(item.subs, (v) => listTypes.includes(v.type));
return {
type: item.type,
embedded: [
...nonLists,
{
type: "list",
items: lists
}
]
}
}
const groupedData = contentData.data.content.reduce((acc, cur) => {
//Check if this indexed array already exists, if not create it.
const currentArray = (acc[`${cur.type}-group`] && acc[`${cur.type}-group`].items) || [];
const flattenedItem = flattenSectionsAndSubs(cur);
const embeddedItem = createEmbeddedFromItem(flattenedItem);
return {
...acc,
[`${cur.type}-group`]: {
type: `${cur.type}-group`,
items: [...currentArray, embeddedItem]
}
}
}, {});
console.log(groupedData);
Now this doesn't exactly match what you've asked for - but it should probably work.
You can add your own bits into only add a list item, if the array isn't empty, and to stop the column from being in its own group.
The thing is - tbh it seems like a little bit of a red flag that you would create an array of items that don't having matching structures, which is why I've done it this way.

Getting [[Object]] when saving JSON

i am trying to save a json with "somewhere".
This function is incomplete but its enough to show the problem:
function testJSON(products) {
var productsPromises = products.map(function(product) {
var title = product['Title'];
var stock = product['Stock'];
var price = product['Price'];
if (stock == "Disponible") {
stock = true;
} else {
stock = false;
}
var toPush = [{Stock: stock, Price: price}];
var results = {Title: title, Results: toPush};
db.connect('./xxxxx/results.json');
var find = db.find('Productos', {Title: title});
console.log(find);
});
return Promise.all(productsPromises);
}
That returns:
[ { Title: 'Grabador de voz ISD1932',
Results: [ [Object] ],
id: 'f4099bff-fc55-4697-b712-d84343931818' } ]
[ { Title: 'Arduino SD Card Shield',
Results: [ [Object] ],
id: '75c79411-a905-41b3-9578-bb7072139a4d' } ]
[ { Title: 'Placa prototipo con zócalo para microSD Transflash',
Results: [ [Object] ],
id: 'af21962a-197e-43db-aba2-779be95357f2' } ]
[ { Title: 'Frontal para LCD 32PTU (Negro)',
Results: [ [Object] ],
id: '29d1e6cd-b549-44ad-87af-e4a4a056a609' } ]
I saved it same way but using
db.save('Productos', results); //instead of db.find(...
Why am i getting [[Object]] instead of the data? How can i fix this?
I suppose db.save('Productos', JSON.stringify(results)); should do it.

Categories

Resources