Js / Node.js - 如何使用动态键名称将对象添加到对象?

Pik*_*ikk 1 javascript node.js

我需要将歌曲添加到 .json 文件中。json 是一个对象,有内部对象。

{
  "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"
  }
}
Run Code Online (Sandbox Code Playgroud)

在上面的 json 中通过运行函数添加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))

};
Run Code Online (Sandbox Code Playgroud)

问题是对象的键需要与标题相同。所以而不是

"title": {
        "title": "yyyy",
        "author": "",
        "date": "ggggg"
      }
Run Code Online (Sandbox Code Playgroud)

它应该保存

"yyyy": {
        "title": "yyyy",
        "author": "",
        "date": "ggggg"
      }
Run Code Online (Sandbox Code Playgroud)

为了修复它原来是一个字符串:

  const newSong = {
    "title": {
      "title": title,
      "author": author,
      "date": date
    }
  }
Run Code Online (Sandbox Code Playgroud)

所以我删除了字符串引号...但仍然相同。

我该如何解决这个问题?

Ion*_*zău 6

要将值动态设置title为键,请使用以下[title]: ...表示法:

const newSong = {
  [title]: {
    "title": title,
    "author": author,
    "date": date
  }
}
Run Code Online (Sandbox Code Playgroud)

另外,请勿使用,await fs.readFileSync因为readFileSync 会返回值。相反,使用await fs.promises.readFile它使用承诺:

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))

};
Run Code Online (Sandbox Code Playgroud)