Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
Js / Node.js - How to add an object to object, with a dynamic key name?

I need to add a song to a .json file. The json is an object, with inside objects.

{
  "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"
  }
}

In the json above was added by running the function 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))

};

The problem is that the key of the object needs to be the same as the title. So instead of

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

it should save

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

In order to fix that it originall was as a string:

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

so I removed the string quotes... but stil the same.

How can I fix that?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

To dynamically set the title value as the key, use the [title]: ... notation:

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

Also, do not use await fs.readFileSync because readFileSync returns the value. Instead, use await fs.promises.readFile which uses promises:

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 Denunciar

0

Use the following code :

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda