Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

229
Views
Js/Node.js - ¿Cómo agregar un objeto a objeto, con un nombre de clave dinámica?

Necesito agregar una canción a un archivo .json. El json es un objeto, con objetos internos.

 { "Song title 1": { "title": "Song title 1", "author": "Song author 1", "date": "1894" }, "Song title 2": { "title": "Song title 2", "author": "Song author 2", "date": "2000" }, "title": { "title": "yyyy", "author": "", "date": "ggggg" } }

En el json anterior se agregó ejecutando la función saveSongs("yyyy", "", "ggggg")

 export const saveSongs = async (title, author, date) => { const songs = JSON.parse(await fs.readFileSync( 'songs.json', 'utf-8' )); const newSong = { title: { "title": title, "author": author, "date": date } } const updatedBookList = Object.assign(song, newSong) console.log(updatedSongList); fs.writeFileSync("songs.json", JSON.stringify(updatedSongList)) };

El problema es que la clave del objeto debe ser la misma que la del título. Entonces, en lugar de

 "title": { "title": "yyyy", "author": "", "date": "ggggg" }

debería guardar

 "yyyy": { "title": "yyyy", "author": "", "date": "ggggg" }

Para arreglar que originalmente era como una cadena:

 const newSong = { "title": { "title": title, "author": author, "date": date } }

así que eliminé las comillas de cadena... pero sigue igual.

¿Cómo puedo arreglar eso?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Para establecer dinámicamente el valor del title como clave, utilice la notación [title]: ... :

 const newSong = { [title]: { "title": title, "author": author, "date": date } }

Además, no use await fs.readFileSync porque readFileSync devuelve el valor. En su lugar, use await fs.promises.readFile que usa promesas:

 export const saveSongs = async (title, author, date) => { const songs = JSON.parse(await fs.promises.readFile( 'songs.json', 'utf-8' )); const newSong = { [title]: { "title": title, "author": author, "date": date } } const updatedBookList = Object.assign(song, newSong) console.log(updatedSongList); await fs.promises.writeFile("songs.json", JSON.stringify(updatedSongList)) };
about 4 years ago · Juan Pablo Isaza Report

0

Usa el siguiente código:

const nuevaCanción = { [título]: { "título": título, "autor": autor, "fecha": fecha } }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!