All files / datamodel/src/converter flat-json.js

100% Statements 14/14
100% Branches 2/2
100% Functions 2/2
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                                                          110x 110x   110x 110x   110x 367x 367x 1497x 1068x   429x 429x   1497x   367x     110x        
import { columnMajor } from '../utils';
 
/**
 * Parses and converts data formatted in JSON to a manageable internal format.
 *
 * @param {Array.<Object>} arr - The input data formatted in JSON.
 * @return {Array.<Object>} Returns an array of headers and column major data.
 * @example
 *
 * // Sample input data:
 * const data = [
 *    {
 *      "a": 1,
 *      "b": 2,
 *      "c": 3
 *    },
 *    {
 *      "a": 4,
 *      "b": 5,
 *      "c": 6
 *    },
 *    {
 *      "a": 7,
 *      "b": 8,
 *      "c": 9
 *    }
 * ];
 */
function FlatJSON (arr) {
    const header = {};
    let i = 0;
    let insertionIndex;
    const columns = [];
    const push = columnMajor(columns);
 
    arr.forEach((item) => {
        const fields = [];
        for (let key in item) {
            if (key in header) {
                insertionIndex = header[key];
            } else {
                header[key] = i++;
                insertionIndex = i - 1;
            }
            fields[insertionIndex] = item[key];
        }
        push(...fields);
    });
 
    return [Object.keys(header), columns];
}
 
export default FlatJSON;