1

I need to take data from a CSV file and attach it to the main JSON I use for my Angular app.

More specifically, I need to take the life expectancies from the CSV file and attach them to the matching country of the JSON (the JSON data is an array of objects, of length 212 and the CSV data is of length 200).

I use d3.js to parse the CSV file. I tried this but it doesn't seem to work. The getData method that I subscribe, is the main source of data, in which I want to attach life expectancy.

this.store.getData().subscribe((data: Data[]) => {
        
      d3.csv('../assets/datasets/life_expectancy.csv').then((csvData: any) => {
          
        for (let i = 0; i < csvData.length; i++) {
          if (csvData[i].country_name === data[i].country) {
            data[i].lifeExpectancy = csvData[i].country_life_expectancy;
          }
        }
          
      });

The life expectancy CSV is like this ([{country_name: 'United States', {country_life_expextancy: 79.11}}...])

1 Answer 1

1

Finally, I came up with a solution:

data: Data[];

      ngOnInit() {
        this.store.getData().subscribe((data: Data[]) => {
          this.data = data;
          d3.csv('../assets/datasets/life_expectancy.csv').then((csvData: any) => {
            for (let i = 0; i < csvData.length; i++) {
              for (let j = 0; j < this.data.length; j++) {
                if (csvData[i].country_name === this.data[j].country) {
                  this.data[j].lifeExpectancy = csvData[i].country_life_expectancy;
                }
              }
            }
          });
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.