如何匹配来自两个 JSON 文件的 id 键,然后用更改更新源 JSON

How to match id key from two JSON files then update the source JSON with changes

这有点复杂,但我相信 Whosebug 编码天才会轻松掌握(菜鸟的荣誉)。我有一个 source.json 文件和一个 changes.json 文件。在更改文件中,我有更新、创建、删除等的 CRUD 类型指令。这是我正在构建的节点中的命令行工具。

要更新播放列表条目,我必须将更改中的 payload.id 与原始文件中的 playlist.id 相匹配...然后我假设 delete.json()原始条目并改变更改。为清楚起见,我只需要更新部分的帮助。不确定如何在源和更改中匹配 id。我猜是 .filter() 还是 .reduce()?

source.json:

"playlists" : [
      {
        "id" : "1",
        "owner_id" : "2",
        "song_ids" : [
          "8",
          "32"
        ]
      }
]

changes.json:

"playlists": [{
            "action": "update",
            "payload": [{
                "id": "1",
                "owner_id": "2",
                "song_ids": [
                    "8"
                ]
            }]
        }

期望的输出写入output.json

"playlists" : [
      {
        "id" : "1",
        "owner_id" : "2",
        "song_ids" : [
          "8"
        ]
      }
]

到目前为止,我的代码运行良好,但不知道如何将来自源 (playlist.id) 的 id 与更改 (payload.id) 相匹配,如果匹配,从源中删除记录并替换为我的更改记录。我认为它需要只是 if 子句的 update 部分中的子例程,然后是 .push()。谢谢大家!

    // Stream in source file
    const data = JSON.parse(fs.readFileSync('./' + inputFile));

    // Stream in changes file
    const changes = JSON.parse(fs.readFileSync('./' + changesFile));

    for(const [table, actions] of Object.entries(changes)) {
        console.log([table]);
        if(!(table in data))continue;
        
        // iterate through inner CRUD directives and mutate payloads
        for(const actionDetail of actions) {
            if(actionDetail.action === 'create') {
                console.log('This is a CREATE entry');
                data[table].push(...actionDetail.payload);
            }

            if(actionDetail.action === 'delete') {
                console.log('This is a DELETE entry');
            }

            if(actionDetail.action === 'update') {
                console.log('This is a UPDATE entry');
                // const something = (is (source)payload.id === (changes)playlist.id) {
                //     if so, delete source entry and push new entry
                //     data[table].push(...actionDetail.payload);
                //}
            }

        }
    }
    fs.writeFileSync('output.json', JSON.stringify(data, null, 2));

如果我正确理解了你的数据集并应用了你想要改变你的初始数据对象的事实,你可以这样:

console.log('This is a UPDATE entry');
actionDetail.payload.forEach((payload) => {
  const index = data.playlists.findIndex(
    (playlist) => playlist.id === payload.id
  );
  if (index > -1) data.playlists[index] = payload;
});