I am trying to append an id to an object if it's the first and if there are others I want to add +1 to one that I am adding.
I am using function that is called save
and inside it there is a writeFile
and an appendFile
method:
class Contenedor {
constructor (nombre){
this.nombre= nombre
this.count = 0
this.product = []
}
save(obj) {
if (this.count <= 1){
fs.writeFile(`./${this.nombre}`, JSON.stringify(obj), 'utf-8', (err)=> {
if (err) {
console.log("Error al crear archivo")
} else {
this.product.map(x=>{
x['id'] = this.count;
this.count++
})
console.log("Archivo creado")
}
})
} else {
fs.appendFile(`./${this.nombre}`, JSON.stringify(obj), 'utf-8', (err)=> {
if (err) {
console.log("Error al crear archivo")
} else {
this.product.map(x=>{
x['id'] = this.count;
this.count++
})
console.log("Archivo agregado")
}
})
}
}
}
let archivos = new Contenedor('text.json')
archivos.save(
[
{
title: 'Escuadra',
price: 152.50,
thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.seawhite.co.uk%2Fimagecache%2F6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
}
]
I want to have a unique id for the objects. I'm using map()
method and already tried this.count++
.
Anyone knows how to do it?