【问题标题】:Convert csv to object key value pair using js使用js将csv转换为对象键值对
【发布时间】:2021-12-15 06:24:16
【问题描述】:

我正在尝试将 CSV 数据转换为键值对数组。我有一个像下面这样的 CSV,请看一下。

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

我的预期输出

{
    "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)",

    }    
}

Attrname 是键,AttrValue 是这里的值。需要按 Flag 或 AttrUnit 分组。

我的代码如下。

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)
    })

我的实际输出

[
  { 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)"]' }
  }
]

邮件密钥未在此处分组,我无法合并它。

【问题讨论】:

    标签: javascript node.js arrays json object


    【解决方案1】:

    每个keydata.push 都会在数组中创建新项目。这就是为什么项目不按标题分组的原因。 将 data = [] 从数组更改为对象:data = {}。并使用而不是 data.push 这个:

    // 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;
    

    【讨论】:

    • 非常感谢您挽救了我的一天。但一个问题是第一个标题不是字符串。请检查以下。 { 显示器:{ 类型:['LTPS IPS LCD'],尺寸:['6.3 英寸,99.1 cm2']},'显示器型号':{分辨率:['1080 x 2280 像素,19:9 比例'],尺寸: [ '6.3 英寸,99.1 cm2 (~82.5% 屏占比)' ] } }
    • DISPLAY 是一个有效的标识符名称,这就是在向数据添加此类键时缺少引号的原因。但是DISPLAY 实际上是一个字符串,缺少引号只是为了样式。你可以检查这个电话data['DISPLAY']。 'DISPLAY' 是一个字符串,无论如何您都可以访问嵌套属性。
    • 谢谢。你能解释一下这条线是什么意思 const newData = data[heading] 吗? {};
    • @ramesh 我已经更新了我的答案。 ?? 是空值合并运算符:如果左侧为空,则何时使用右侧。
    • 非常感谢。如果可能,请分享任何教程链接学习 JS 中的对象和数组概念
    猜你喜欢
    • 2021-11-03
    • 2016-03-18
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多