在 node.js 中从一个函数传递到另一个函数时数据损坏

Data Getting Corrupted while passing from one function to another in node.js

我有一个函数应该从一个函数中获取一组对象,处理数组中的对象,然后 return 一个指定的输出。下面是上述功能;

function extractData(newResult) {
  try {
    const data = [];
    data.push(Object.keys(newResult[0]));

    for (let i = 0; i < newResult.length; i++) {
      data.push(Object.values(newResult[i]));
    }
    return data;
  } catch (error) {}
}

async function exportToCSV() {
  try {
    // const { title, emailAddress } = req.body;
    const spreadsheetId = await createSpreadsheet(
      "test",
      "xyz@gmail.com"
    );
    const result = await account.findAll();
    const newResult = JSON.stringify(result, null, 2);
    console.log(newResult);
    const data = extractData(newResult);
    console.log(data);
    const response = await writeToSpreadsheet(spreadsheetId, data);
    // console.log(response);
  } catch (error) {}
}

extractData(newResult) 函数应该接收下面的输入,该输入包含在 exportToCSV() 函数的 newResult 变量中...

[
  {
    "id": 1,
    "auth_id": "20S0KPNOIM",
    "username": "azr1"
  },
  {
    "id": 2,
    "auth_id": "54P2EOKQ47",
    "username": "azr2"
  },
  {
    "id": 3,
    "auth_id": "9LLV6I4ZWI",
    "username": "azr3"
  },
  {
    "id": 4,
    "auth_id": "YHWE3HDLPQ",
    "username": "azr4"
  },
  {
    "id": 5,
    "auth_id": "6DLH8A25XZ",
    "username": "azr5"
  }
]

...并在下面给出此输出;

[
  [ 'id', 'auth_id', 'username' ],
  [ 1, '20S0KPNOIM', 'azr1' ],
  [ 2, '54P2EOKQ47', 'azr2' ],
  [ 3, '9LLV6I4ZWI', 'azr3' ],
  [ 4, 'YHWE3HDLPQ', 'azr4' ],
  [ 5, '6DLH8A25XZ', 'azr5' ]
]

但是,我得到了这个;

[
  [ '0' ],  [ '[' ],  [ '\n' ], [ ' ' ],  [ ' ' ],  [ '{' ],
  [ '\n' ], [ ' ' ],  [ ' ' ],  [ ' ' ],  [ ' ' ],  [ '"' ],
  [ 'i' ],  [ 'd' ],  [ '"' ],  [ ':' ],  [ ' ' ],  [ '1' ],
  [ ',' ],  [ '\n' ], [ ' ' ],  [ ' ' ],  [ ' ' ],  [ ' ' ],
  [ '"' ],  [ 'a' ],  [ 'u' ],  [ 't' ],  [ 'h' ],  [ '_' ],
  [ 'i' ],  [ 'd' ],  [ '"' ],  [ ':' ],  [ ' ' ],  [ '"' ],
  [ '2' ],  [ '0' ],  [ 'S' ],  [ '0' ],  [ 'K' ],  [ 'P' ],
  [ 'N' ],  [ 'O' ],  [ 'I' ],  [ 'M' ],  [ '"' ],  [ ',' ],
  [ '\n' ], [ ' ' ],  [ ' ' ],  [ ' ' ],  [ ' ' ],  [ '"' ],
  [ 'u' ],  [ 's' ],  [ 'e' ],  [ 'r' ],  [ 'n' ],  [ 'a' ],
  [ 'm' ],  [ 'e' ],  [ '"' ],  [ ':' ],  [ ' ' ],  [ '"' ],
  [ 'a' ],  [ 'z' ],  [ 'r' ],  [ '1' ],  [ '"' ],  [ '\n' ],
  [ ' ' ],  [ ' ' ],  [ '}' ],  [ ',' ],  [ '\n' ], [ ' ' ],
  [ ' ' ],  [ '{' ],  [ '\n' ], [ ' ' ],  [ ' ' ],  [ ' ' ],
  [ ' ' ],  [ '"' ],  [ 'i' ],  [ 'd' ],  [ '"' ],  [ ':' ],
  [ ' ' ],  [ '2' ],  [ ',' ],  [ '\n' ], [ ' ' ],  [ ' ' ],
  [ ' ' ],  [ ' ' ],  [ '"' ],  [ 'a' ],
  ... 273 more items
]

下面介绍的是实现所需 objective.

的一种可能方法

代码段

const myTransform = arr => {
  const keysArr = arr.reduce(
    (acc, itm) => (
      Object
      .keys(itm)
      .filter(k => !acc.includes(k))
      .forEach(k => acc.push(k)),
      acc
    ),
    []
  );
  return (
    [keysArr]
    .concat(
      arr.map(
        obj => (
          keysArr.map(
            k => obj?.[k] ?? ''
          )
        )
      )
    )
  );
};

/* code with explnation
// method to transform the given array
const myTransform = arr => {
  // first collect all unique keys into "keysArr" array
  const keysArr = dataArr.reduce(
    // here, ".reduce()" is used with "acc" as the accumulator
    (acc, itm) => (     // "itm" is the iterator (ie, elt of "arr" array)
      Object
      .keys(itm)        // get all keys from iterator "itm"
      .filter(k => !acc.includes(k))    // discard keys already in "acc"
      .forEach(k => acc.push(k)),       // push remaining keys into "acc"
      acc               // return "acc"
    ),
    []                  // initialize "acc" as an empty array "[]"
  );
  // now, return the transformed array
  return (
    [keysArr]           // first elt is the array of keys
    .concat(            // concat to this, array of values from each "arr" elt
      arr.map(          // iterate over "arr" using ".map()"
        obj => (        // the iterator (ie, each elt of "arr") is "obj"
          keysArr.map(  // iterate over the keys array
            k => obj?.[k] ?? ''   // pick the value from "obj" or, keep empty-string
          )
        )               // implicit return from both ".map()" returns nested array
      )
    )
  );
};
*/

const dataArr = [
  {
    "id": 1,
    "auth_id": "20S0KPNOIM",
    "username": "azr1"
  },
  {
    "id": 2,
    "auth_id": "54P2EOKQ47",
    "username": "azr2"
  },
  {
    "id": 3,
    "auth_id": "9LLV6I4ZWI",
    "username": "azr3"
  },
  {
    "id": 4,
    "auth_id": "YHWE3HDLPQ",
    "username": "azr4"
  },
  {
    "id": 5,
    "auth_id": "6DLH8A25XZ",
    "username": "azr5"
  }
];

console.log('transformed arr is:\n', myTransform(dataArr));
.as-console-wrapper { max-height: 100% !important; top: 0 }

说明

在上面的代码段中添加了内联评论。

目前您正在尝试对字符串值应用 Object.keysObject.values。 你可以试试这个功能。

async function exportToCSV() {
  try {
    // const { title, emailAddress } = req.body;
    const spreadsheetId = await createSpreadsheet(
      "test",
      "xyz@gmail.com"
    );
    const result = await account.findAll();
    let newResult = JSON.stringify(result, null, 2);
    // JUST NEED TO PARSE AFTER YOU STRINGIFY IT....
    newResult = JSON.parse(newResult);
    console.log(newResult);
    const data = extractData(newResult);
    console.log(data);
    const response = await writeToSpreadsheet(spreadsheetId, data);
    // console.log(response);
  } catch (error) {}
}

我添加了一行代码并带有注释。

let newResult = JSON.stringify(result, null, 2);
    // JUST NEED TO PARSE AFTER YOU STRINGIFY IT....
    newResult = JSON.parse(newResult);

我认为它可以解决您的问题。