【问题标题】:Is there an npm package that will convert unstructured data to csv?是否有将非结构化数据转换为 csv 的 npm 包?
【发布时间】:2019-09-16 23:44:50
【问题描述】:

试图在 Javascript 中将一些数据导出到 csv 中。试图找到一个 npm 模块来执行此操作......但是 - 我拥有的数据每行可能有不同的标题......

例如我的数据可能是这样的:

[ { name: 'John', color: 'Blue', age: 25 }, { name: 'Ursula', color: 'Red', food: 'pasta'},...]

理想情况下,csv 会导出到这个:

name, color, age, food
John, Blue, 25,
Ursula, Red,,pasta

我已经查看了fast-csv,它似乎无法满足动态标头(上述需求)...(在上面的示例中,fast-csv 将仅由第一个条目提供静态标头(只有name,colorage))

【问题讨论】:

  • 这些数据并不是真正的“非结构化”,它只是有一些可选字段。
  • 不反对使用与“非结构化”不同的词来更改标题 - 我也不认为附加字段是“可选的”。
  • 嗯,其中一些并不总是为任何给定的记录填写,因此很明显,输入数据的人必须有一定的空间来完成每个字段。或者你是说他们可以任意声明他们喜欢的任何属性,所以下一条记录可能包含“牛仔裤:蓝色”或其他完全不可预测的东西?是否存在有限的可能字段列表?
  • @ADyson,是的 - 下一条记录可能包含“牛仔裤:蓝色”。这是可能的——每条记录都是完全不可预测的。

标签: javascript node.js npm export-to-csv node-modules


【解决方案1】:

这里有一些代码将根据对象中具有不同键名的类似数据结构生成输出。

const data = [{ name: 'John', color: 'Blue', age: 25 }, { name: 'Ursula', color: 'Red', food: 'pasta'}, { size: 12, feet: 'small', name: 'Bob'}];

function getHeadings(data) {

  // `reduces` over the array combining all the
  // different object keys into one array
  // removing the duplicates by converting it to a
  // Set, and then converting it back to an array again
  return [...new Set(data.reduce((acc, c) => {
    const keys = Object.keys(c);
    return acc.concat(keys);
  }, []))];
}

const headings = getHeadings(data);

// Iterate over the data...
const out = data.reduce((acc, c) => {

  // ...grab the keys in each object
  const keys = Object.keys(c);

  // ...create a new array filled with commas
  const arr = Array(headings.length).fill(',');

  // For each key...
  keys.forEach(key => {

    // ...find its index in the headings array
    const index = headings.findIndex(el => el === key);

    // ...and replace the comma in the array with the key
    arr[index] = `${c[key]},`;
  });
 
  // Add the array to the output
  return acc.concat(arr.join(''));
}, []).join('\n');

console.log(`${headings}\n${out}`);

【讨论】:

    猜你喜欢
    • 2016-02-16
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 2015-01-05
    • 1970-01-01
    相关资源
    最近更新 更多