【问题标题】:String to array (object) Angular TS 12字符串到数组(对象)Angular TS 12
【发布时间】:2021-11-11 12:58:09
【问题描述】:

我有一个 CSV 文件(本地),将其转换为字符串,部分字符串如下:

44,"3845657"
51,"3847489"
1,"3888510"
79,"3840471"
57,"3864492"

收到输入数字(第一个值)后,我想将其与第二个值(字符串)匹配。

所以如果输入是 51,我希望能够返回 3847489。 csv 中没有标题。

CSV 转字符串:

  fetchData() {
    fetch('../../../assets/static/mapping.csv')
      .then(response => response.text())
      .then(data => {
        // Do something with your data
        console.log(data);
        this.mappingCSV = data;
      });
  }

输出:

44,"3845657" 
51,"3847489"
1,"3888510"
79,"3840471"
57,"3864492"

也欢迎使用其他将 csv 转换为对象数组的方法,不要与我的 csv 到字符串方法结合。

【问题讨论】:

  • 所以你希望你的最终数组显示为 [{44: 3545657}, {51: 3847489}] 或者你希望它是 [{Id: 44, Text: 3545657}, {Id: 51、文字:3847489}]?
  • 第二个会很棒

标签: arrays angular typescript csv mapping


【解决方案1】:

我在本例中使用 HTTPClient,它是 Angular 中可用的内置服务类。这里how使用Angular的HTTPClient供你阅读和了解它的好处。

在我的 .ts 文件中,我首先将文本转换的 csv 拆分为任何换行符。然后我添加了一个循环,在其中我用逗号分割文本并将必要的细节推送到新的 csvArray。

export class SampleComponent {
  public csvArr: CsvArray[] = [];
  constructor(private http: HttpClient) {
    this.http.get('assets/csv.csv', {
      responseType: 'text'
    }).subscribe(
      (data) => {
        const csvToRowArray = data.split('\n');
        console.log(csvToRowArray);
        for (let index = 0; index < csvToRowArray.length; index++) {
          const row = csvToRowArray[index].split(',');
          this.csvArr.push(new CsvArray(parseInt(row[0], 10), row[1]));
        }
        console.log(this.csvArr);
      },
      (error) => {
        console.log(error);
      }
    );
  }
}

export class CsvArray {
  id: number;
  text: string;

  constructor(id: number, text: string) {
    this.id = id;
    this.text = text;
  }
}

我创建了一个stackblitz,以便您检查我的实现。

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 2021-08-08
    • 1970-01-01
    • 2023-02-20
    • 2014-07-27
    相关资源
    最近更新 更多