0

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.

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks a lot you saved my day. But one problem is the first heading is not coming as string. Please check below. { DISPLAY: { Type: [ 'LTPS IPS LCD' ], Size: [ '6.3 inches, 99.1 cm2' ] }, 'DISPLAY Model': { Resolution: [ '1080 x 2280 pixels, 19:9 ratio' ], Size: [ '6.3 inches, 99.1 cm2 (~82.5% screen-to-body ratio)' ] } }
DISPLAY is a valid identifier name that is why quote are missing when you add such key to data. But DISPLAY is actually a string and missing quote is just for style. You can check this calling data['DISPLAY']. 'DISPLAY' is a string and you can access nested properties anyway.
Thanks. Could you please explain what this line means const newData = data[heading] ?? {};
@ramesh I have updated my answer. ?? is nullish coalescing operator: if left side is null, when will be used right side.
Thanks a lot. If possible please share any tutorial links learning object & array concept in JS

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.