Javascript(NodeJs) - 将数组和对象转换为mysql中的批量插入(Sequelize)

时间:2017-12-18 09:20:55

标签: javascript mysql arrays json node.js

这是我的json:

{
    "senderName": "ifelse",
    "message": "Hi",
    "groups": [
    {
        "id": 14,
        "groupname": "Angular",
        "contactgroups": [
        {
            "id": 1,
            "contact": {
                "id": 1,
                "gsm": "123456789"
            }
        },
        {
            "id": 3,
            "contact": {
                "id": 2,
                "gsm": "111111111"
            }
        }],
        "select": true
    }],
    "draftData": {
        "contacts": [
        ]
    }
}

如何将上面的json变成:

[{phoneno: 123456789; sender: ifelse ; message: Hi},{phoneno: 11111111; sender: ifelse ; message: Hi}]

我想从 gsm 对象键

中获取phoneno数据

哪种方法最好? for或forEach还是其他什么?

1 个答案:

答案 0 :(得分:3)

我想,这就是你想要的。使用mapcontactgroups转换为phoneno的新数组。

var data = {
  "senderName": "ifelse",
  "message": "Hi",
  "groups": [{
    "id": 14,
    "groupname": "Angular",
    "contactgroups": [{
        "id": 1,
        "contact": {
          "id": 1,
          "gsm": "123456789"
        }
      },
      {
        "id": 3,
        "contact": {
          "id": 2,
          "gsm": "111111111"
        }
      }
    ],
    "select": true
  }],
  "draftData": {
    "contacts": []
  }
}

var result = data.groups[0].contactgroups.map(i => {
  return {
    phoneno: i.contact.gsm,
    sender: data.senderName,
    message: data.message
  }
})

console.log(result);