将两个数组组合为键值对

时间:2018-01-03 11:10:52

标签: arrays node.js

我有两个数组如下

        var field_array=["booktitle","bookid","bookauthor"];
        var data_array=["testtitle","testid","testauthor"];

我想将这两个数组合并并将其转换为以下格式

    var data={
    "booktitle":"testtitle",
    "bookid":"testid",
    "bookauthor":"testauthor"
}

我想使用nodejs

将此数据插入数据库
var lastquery= connection.query('INSERT INTO book_tbl SET ?',data, function (error, results, fields) {
  if (error) {

             res.redirect('/list');
  }else{
      res.redirect('/list');
  }
});

请帮我解决这个问题。

3 个答案:

答案 0 :(得分:1)

var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
var finalObj = {};
field_array.forEach(function (eachItem, i) {
  finalObj[eachItem] = data_array[i];
});

console.log(finalObj); //finalObj contains ur data

答案 1 :(得分:0)

您也可以以类似的方式使用reduce()

var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
var result = field_array.reduce((acc, item, i) => {
  acc[item] = data_array[i];
  return acc;
}, {}); 
console.log(result);

答案 2 :(得分:0)

  

在这里,我逐行解释了我的代码。希望它会有所帮助

        var field_array = ["booktitle", "bookid", "bookauthor"];
        var data_array = ["testtitle", "testid", "testauthor"];

        //Convert above two array into JSON Obj
        var jsondata = {};
        field_array.forEach(function (eachItem, i) {
            jsondata[eachItem] = data_array[i];
        });
        //End

        //Store Jsondata into an array according to Database column structure
        var values = [];
        for (var i = 0; i < jsondata.length; i++)
            values.push([jsondata[i].booktitle, jsondata[i].bookid, jsondata[i].bookauthor]);
        //END

        //Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
        connection.query('INSERT INTO book_tbl (booktitle, bookid, bookauthor) VALUES ?', [values], function(err, result) {
        if (err) {
        res.send('Error');
        }
        else {
        res.send('Success');
        }
        //END