简体   繁体   中英

Problems with nested Object.keys forEach loop and building array of merged JSON objects

I have two CSV files, one with routing steps and one with a list of ids. I need to add each id to the start of each routing step. I'm using Node.js.

var routeNumFile = '/routing_numbers.csv';
var routeStepFile = '/routing_steps.csv';

const csvToJson = require('csvtojson');
const jsonToCsv = require('json2csv').parse;
const fs = require('fs');

var routeNumArray;
var routeStepArray;
try {
    routeNumArray = await csvToJson().fromFile(routeNumFile);
} catch (err) {
    console.log("error in reading csv file")
}

try {
    routeStepArray = await csvToJson().fromFile(routeStepFile);
} catch (err) {
    console.log("error in reading csv file")
}

var outputArray = new Array;
var outputPath = '/gitlab/BSI_Create_Csv_Import/finalOutput.csv';

if (routeNumArray != null && routeStepArray != null) {
    Object.keys(routeNumArray).forEach(function (key1) {

        Object.keys(routeStepArray).forEach(function (key2) {

            var comboObj = Object.assign(routeNumArray[key1], routeStepArray[key2]);
            console.log(comboObj);
            outputArray.push(comboObj);
        });

    });
}
console.log(outputArray);


var csv = jsonToCsv(outputArray);
fs.writeFileSync(outputPath, csv);

The output from console.log(comboObj) is what I want. However, when I put that into an array, I just get the very last entry in the routing steps CSV over and over. If I write it using a stream directly where the comboObj is created, it mostly works. If I do that I convert the object to CSV first and the output leaves me with the headings duplicated at the end of every line. It writes much cleaner from an array of JSON objects to a CSV.

So, I'm trying to get all of the combined objects together in an array so I can convert it all to CSV and write it to a file. Can anyone tell me what's going wrong with my method?

您应该创建一个新对象并为其分配属性,如下所示:

var comboObj = Object.assign({}, routeNumArray[key1], routeStepArray[key2]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM