Angular 2 - 从嵌套数组创建CSV文件

时间:2021-05-25 21:29:35

I am trying to create an object for csv file from the nested array which looks something like this -

我试图从嵌套数组创建一个csv文件的对象,看起来像这样 -

[
  {
    "Name":obj.name,
    "Age": obj.age,
    "Class":obj.class
  }
]

I have generated this array using the code which looks something like -

我使用看起来像这样的代码生成了这个数组 -

let obj = originalObj.map(studentObj => {
   return {
     "Name":studentObj.name,
     "Age":studentObj.age,
     "class":studentObj.class
   }
}

Now here the obj.class is an object of comma separated values i.e maths,biology,physics. The number of classes are not fixed and dynamic, what I mean is a person can have 2 classes or 3 or 4 or can have no class at all. The csv i want to generate should look something like this -

现在,obj.class是逗号分隔值的对象,即数学,生物学,物理学。课程的数量不固定和动态,我的意思是一个人可以有2个班级或3个或4个或根本没有班级。我想生成的csv应该看起来像这样 -

| Name | Age | Class     | Class     | Class      |
|------|-----|-----------|-----------|------------|
| abc  | 12  |           |           |            |
| xyz  | 18  | Computers |           |            |
| ijk  | 20  | Astronomy | Geography | Science    |

How do I transform the array object to generate the required object which can generate the csv like above? I would preferably not use any external npm library for this unless it is absolutely necessary.

如何转换数组对象以生成可以生成上述csv的必需对象?除非绝对必要,否则我最好不要使用任何外部npm库。

I did tried with the sample code provided below by @Mr. Ratnadeep and it works well if the number of classes are fixed, but in my case the first record don't have a class hence while converting into csv keys are not getting generated for the class at all. Need help to solve this challenge I am out of my depth.

我尝试过使用@Mr提供的示例代码。 Ratnadeep并且如果类的数量是固定的,它运行良好,但在我的情况下,第一条记录没有类,因此转换为csv键时根本没有为类生成。需要帮助来解决这个挑战我不在我的深度。

2 个解决方案

#1


2  

JSON does not contain the multiple keys with same name. Instead of that I have implemented. Implemented using the sample data in original object, you can modify it as per your need. Name | Age | class1 | class2 | class3 ...

JSON不包含具有相同名称的多个键。而不是我已实施。使用原始对象中的示例数据实现,您可以根据需要进行修改。名称|年龄| class1 | class2 | 3级......

used jsonexport npm package for creating csv.

使用jsonexport npm包创建csv。

var myData = [
  {
    "Name":'John',
    "Age": 28,
    "Classes":"Maths,Biology,Physics"
  }
]

for(var i=0;i<myData.length;i++){
    var arrClass = myData[i].Classes.split (',');
    delete myData[i].Classes
    arrClass.forEach(function(ele,index){
        var keyName = 'class'+(index+1);
        myData[i][keyName]= ele;
    });
}
jsonexport(myData,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
    fs.writeFile('test.csv',csv,function(err){
        console.log(err);
    });
});

Output: Angular 2  - 从嵌套数组创建CSV文件

输出:

  • Updated Answer
  • 更新的答案

I don't have idea how you are generating the csv. But I have prepared the final myData array of json objects. The classes columns are dynamic in nature.

我不知道你是如何生成csv的。但是我已经准备好了json对象的最终myData数组。类列本质上是动态的。

var myData = [
  {
        "Name":'abc',
        "Age": 12 
    },
    {
        "Name": 'xyz',
        "Age": 18,
        "Classes": "Computers"
    },
    {
        "Name": 'ijk',
        "Age": 20,
        "Classes": "Astronomy,Geography,Science"
    }
]

for(var i=0;i<myData.length;i++){
    if (myData[i].hasOwnProperty("Classes")){
        var arrClass = myData[i].Classes.split(',');
        delete myData[i].Classes;
        arrClass.forEach(function (ele, index) {
            var keyName = 'class' + (index + 1);
            myData[i][keyName] = ele;
        });
    }
}
jsonexport(myData,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
    fs.writeFile('test.csv',csv,function(err){
        console.log(err);
    });
});

Output Angular 2  - 从嵌套数组创建CSV文件

产量

#2


1  

The expected result is not a valid CSV. You can't have three columns with the same name. But you can keep your obj.class as a csv string. A naive and incomplete implementation could be:

预期结果不是有效的CSV。您不能有三个具有相同名称的列。但是你可以将你的obj.class保存为csv字符串。一个天真和不完整的实现可能是:

function toCSV(items, separator=';') {
  if (!items.length) return '';

  const columns = Object.keys(items[0]).join(separator);
  const body = items.map(item =>
    Object.values(item).join(separator)
  ).join('\n');

  return columns + '\n' + body;
}

#1


2  

JSON does not contain the multiple keys with same name. Instead of that I have implemented. Implemented using the sample data in original object, you can modify it as per your need. Name | Age | class1 | class2 | class3 ...

JSON不包含具有相同名称的多个键。而不是我已实施。使用原始对象中的示例数据实现,您可以根据需要进行修改。名称|年龄| class1 | class2 | 3级......

used jsonexport npm package for creating csv.

使用jsonexport npm包创建csv。

var myData = [
  {
    "Name":'John',
    "Age": 28,
    "Classes":"Maths,Biology,Physics"
  }
]

for(var i=0;i<myData.length;i++){
    var arrClass = myData[i].Classes.split (',');
    delete myData[i].Classes
    arrClass.forEach(function(ele,index){
        var keyName = 'class'+(index+1);
        myData[i][keyName]= ele;
    });
}
jsonexport(myData,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
    fs.writeFile('test.csv',csv,function(err){
        console.log(err);
    });
});

Output: Angular 2  - 从嵌套数组创建CSV文件

输出:

  • Updated Answer
  • 更新的答案

I don't have idea how you are generating the csv. But I have prepared the final myData array of json objects. The classes columns are dynamic in nature.

我不知道你是如何生成csv的。但是我已经准备好了json对象的最终myData数组。类列本质上是动态的。

var myData = [
  {
        "Name":'abc',
        "Age": 12 
    },
    {
        "Name": 'xyz',
        "Age": 18,
        "Classes": "Computers"
    },
    {
        "Name": 'ijk',
        "Age": 20,
        "Classes": "Astronomy,Geography,Science"
    }
]

for(var i=0;i<myData.length;i++){
    if (myData[i].hasOwnProperty("Classes")){
        var arrClass = myData[i].Classes.split(',');
        delete myData[i].Classes;
        arrClass.forEach(function (ele, index) {
            var keyName = 'class' + (index + 1);
            myData[i][keyName] = ele;
        });
    }
}
jsonexport(myData,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
    fs.writeFile('test.csv',csv,function(err){
        console.log(err);
    });
});

Output Angular 2  - 从嵌套数组创建CSV文件

产量

#2


1  

The expected result is not a valid CSV. You can't have three columns with the same name. But you can keep your obj.class as a csv string. A naive and incomplete implementation could be:

预期结果不是有效的CSV。您不能有三个具有相同名称的列。但是你可以将你的obj.class保存为csv字符串。一个天真和不完整的实现可能是:

function toCSV(items, separator=';') {
  if (!items.length) return '';

  const columns = Object.keys(items[0]).join(separator);
  const body = items.map(item =>
    Object.values(item).join(separator)
  ).join('\n');

  return columns + '\n' + body;
}