[SOLVED] How to read multiple column CSV by changing headers into categories and all values into one column? – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by arbid99

I want to create a multiple-line chart in d3.js, the data is in csv and is organized as follows:

¦Date ¦ Cat A¦ Cat B¦ Cat C¦
¦:———¦:—-:¦:—-:¦—–:¦
¦2019-12-01¦2 ¦6 ¦9 ¦
¦2018-11-02¦4 ¦4 ¦20 ¦

How do I read the data to be arranged into three columns:

¦Date ¦ Category¦ value ¦
¦:———¦:——-:¦——:¦
¦2019-12-01¦CAT A ¦2 ¦
¦2018-11-02¦CAT A ¦4 ¦
¦2019-12-01¦CAT B ¦6 ¦
¦2018-11-02¦CAT B ¦9 ¦

Please note that I would like to ignore one of the columns (CAT C)



Solution

Typically in D3, one imports flattened data and then groups or nests it accordingly. This means (as far as I’m aware) the tools for doing the reverse aren’t quite so natural. In this case it may be straightforward and readable to use vanilla Javascript:

    const data = [
        { Date: '2019-12-01', 'A' : 2, 'B' : 6, 'C' : 9  }, 
        { Date: '2018-11-02', 'A' : 4, 'B' : 4, 'C' : 20 }
    ];
    
    console.log(data)
    
    result = [];
    
    data.forEach(row => {
                 let a = (({ Date, A, B, C }) => ({ Date, A}))(row);
                 result.push(a)
                 let b = (({ Date, A, B, C }) => ({ Date, B}))(row);
                 result.push(b)
                 });
    console.log(result);


This Question was asked in StackOverflow by arbid99 and Answered by stuwilmur, It is licensed under the terms of
CC BY-SA 2.5.CC BY-SA 3.0.CC BY-SA 4.0.

people found this article helpful. What about you?