【问题标题】:Manipulating json before sending to a database在发送到数据库之前操作 json
【发布时间】:2021-09-15 09:42:31
【问题描述】:

我正在使用 node 和 airtable.js 从 Airtable API 中提取一些数据。我在 airtable 数据库中使用链接字段。数据如下:

{
            "id": "recct1MELnXEJGj6Z",
            "fields": {
                "Household": "Betts",
                "Guests": [
                    "recWONC10o06E4IN0",
                    "recLwxndGevZ7HeUG"
                ],
                "Name (from Guests)": [
                    "Margaret",
                    "Terry"
                ]
            },
            "createdTime": "2021-09-11T15:48:51.000Z"
        }

我想在推送到 MongoDB 数据库之前重新格式化,使其看起来像这样:

    {
            "id": "recct1MELnXEJGj6Z",
            "Household": "Betts",
            "Guests": [
                {
                 "_id" : "recWONC10o06E4IN0",
                 "name" : "Margaret"
                 },
                {"_id" : "recLwxndGevZ7HeUG",
                 "name" : "Terry"
                },
              ],
            "createdTime": "2021-09-11T15:48:51.000Z"
        }

提前致谢

【问题讨论】:

    标签: javascript airtable


    【解决方案1】:

    您基本上需要从fields对象中提取键和值,直接将它们分配给JSON,然后删除fields对象。

    const json = {
      "id": "recct1MELnXEJGj6Z",
      "fields": {
          "Household": "Betts",
          "Guests": [
              "recWONC10o06E4IN0",
              "recLwxndGevZ7HeUG"
          ],
          "Name (from Guests)": [
              "Margaret",
              "Terry"
          ]
      },
      "createdTime": "2021-09-11T15:48:51.000Z"
    }
    
    Object.entries(json.fields).forEach(([key, value]) => (json[key] = value));
    delete json.fields;
    
    console.log(json);

    或者你可以像这样创建一个新的 JSON 对象:

    const json = {
      "id": "recct1MELnXEJGj6Z",
      "fields": {
          "Household": "Betts",
          "Guests": [
              "recWONC10o06E4IN0",
              "recLwxndGevZ7HeUG"
          ],
          "Name (from Guests)": [
              "Margaret",
              "Terry"
          ]
      },
      "createdTime": "2021-09-11T15:48:51.000Z"
    }
    
    const newJson = {...json, ...json.fields};
    delete newJson.fields;
    console.log(newJson);

    【讨论】:

    • 您好,谢谢您的回答,不幸的是,我需要的结果是删除“姓名(来自客人)并创建一个新数组,其中键值为 _id:name 请参阅原始问题。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 2017-06-05
    • 1970-01-01
    • 2012-02-22
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多