Home > database >  Convert csv to object key value pair using js
Convert csv to object key value pair using js

Time:10-31

I'm trying to convert CSV data as a key-value pair array. I have a CSV like this below please take a look.

Attrname1,AttrValue1,AttrUnit1,Flag1,Attrname2,AttrValue2,AttrUnit2,Flag2,Attrname3,AttrValue3,AttrUnit3,Flag3,Attrname4,AttrValue4,AttrUnit4,Flag4,Attrname5,AttrValue5,AttrUnit5,Flag5
Type,"LTPS IPS LCD",DISPLAY,DISPLAY,Size,"6.3 inches, 99.1 cm2 ",DISPLAY,DISPLAY,Resolution,"1080 x 2280 pixels, 19:9 ratio ",DISPLAY Model,DISPLAY Model,Type,"LTPS IPS, 16M colors",Ram,DISPLAY Model,Size,"6.3 inches, 99.1 cm2 (~82.5% screen-to-body ratio)",DISPLAY Model,DISPLAY Model

My expected output

{
    "Display":{
        "Type":"LTPS IPS LCD",
        "Size":"6.3 inches, 99.1 cm2 ",
        "Resolution":"1080 x 2280 pixels, 19:9 ratio "
    },
    "DISPLAY Model":{
        "Type":"LTPS IPS, 16M colors",
        "Size":"6.3 inches, 99.1 cm2 (~82.5% screen-to-body ratio)",

    }    
}

The Attrname is key and AttrValue is value here. Which needs to be grouped by Flag or AttrUnit.

My code is below.

var http = require('http');
var express = require('express');
var port = process.env.PORT || 8089;
var app = express();
var appRoutes = require('./routes/appRoutes');
var bodyParser = require('body-parser');
var cors = require('cors');
app.use(express.static('public'));
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', appRoutes);
http.createServer(app).listen(port);
const csvFilePath = 'test.csv'
const csv = require('csvtojson')
var jsonToCSV = require('json-to-csv');
const { json } = require('body-parser');
const fileName = 'save-html2.csv';
let data = [];
csv()
    .fromFile(csvFilePath)
    .then((jsonObjj) => {
        // console.log(jsonObj);
        jsonObjj.forEach((jsonObj, jsonObj_index) => {
            Object.keys(jsonObj).forEach((objs, objs_index) => {

                if (jsonObj['Flag'   objs_index] == jsonObj['AttrUnit'   objs_index]) {
                    if (jsonObj['Attrname'   objs_index] != undefined) {
                        // data[jsonObj['AttrUnit' objs_index]] =  data[jsonObj['AttrValue' objs_index]]
                        let heading = jsonObj['AttrUnit'   objs_index];
                        let key = [jsonObj['Attrname'   objs_index]];
                        let value = [jsonObj['AttrValue'   objs_index]];
                        data.push({
                            [heading]: {
                                [key]: JSON.stringify(value)
                            }
                        })

                    }
                }
            })
        })
        console.log(data)
    })

My Actual output

[
  { DISPLAY: { Type: '["LTPS IPS LCD"]' } },
  { DISPLAY: { Size: '["6.3 inches, 99.1 cm2"]' } },
  {
    'DISPLAY Model': { Resolution: '["1080 x 2280 pixels, 19:9 ratio"]' }
  },
  {
    'DISPLAY Model': { Size: '["6.3 inches, 99.1 cm2 (~82.5% screen-to-body ratio)"]' }
  }
]

The mail key is not grouping here and I couldn't merge it.

CodePudding user response:

Every key with data.push you create new item in the array. That is why items don`t group by heading. Change data = [] from array to object: data = {}. And use instead of data.push this one:

// Try get current value of heading key. If there is nor such value, create new object.
const newData = data[heading] ?? {};
newData[key] =  JSON.stringify(value);
data[heading] = newData;
  • Related