简体   繁体   中英

Issue while converting array from one format to another

I have the following input array(It's a Javascript Object[] Array response):

[
    {index:1, headerCSV:"Name", dataFields: ["Name", "Id"]},
    {index:2, headerCSV:"Id", dataFields: ["Test", "Test 1"]},
    {index:3, headerCSV:"fname", dataFields: ["Test", "Test 1"]},
    {index:4, headerCSV:"lname", dataFields: []},
]

I am trying to convert it to the following array:

[
    {"header" : 1, "field" :"Name"},
    {"header" : 1, "field" :"Id"},
    {"header" : 2, "field" :"Test"},
    {"header" : 2, "field" :"Test 1"},
    {"header" : 3, "field" :"Test"},
    {"header" : 3, "field" :"Test 1"}
]

In the result array I'll need to put in the header with the input array index and in the field I'll need to construct using the array of the dataFields array of the input array. I have tried with the following code:

var CSVHeadersAndFields = /* The input array */;
var headerFieldMappingJSON = [];
for(var i=0; i<CSVHeadersAndFields.length;i++) {
    headerFieldMappingJSON[i] = {};
    var selectedFields = CSVHeadersAndFields[i].dataFields;
    for(var j=0; j<selectedFields.length;j++) {
        headerFieldMappingJSON[i].header = CSVHeadersAndFields[i].index;
        headerFieldMappingJSON[i].field = selectedFields[j];
    }
}

But I have got the following result:

[
    {"header":1,"field":"Name"},
    {"header":2,"field":"Test"},
    {"header":3,"field":"Test"},
    {}
]

I suspect form the for loop 1st iteration value is replaced by the second iteration and also I'll need to avoid to construct the output array mapping from the empty array of dataFields from the input array.

How to make a correct algorithm to convert the array?

Make a separate iterator index for the result array. Or just push to the result array instead of adding values by index:

var CSVHeadersAndFields = /* The array from question */;
var headerFieldMappingJSON = [];
for(var i = 0; i < CSVHeadersAndFields.length; i++) {
    var selectedFields = CSVHeadersAndFields[i].dataFields;
    for(var j = 0; j < selectedFields.length; j++) {
        headerFieldMappingJSON.push({
            header: CSVHeadersAndFields[i].index,
            field: selectedFields[j]
        });
    }
}

The same example but cleaner:

var input = /* The array from question */;
var output = [];

input.forEach(function (csvRow) {
    csvRow.dataFields.forEach(function (field) {
        output.push({
            header: csvRow.index,
            field: field
        });
    });
});

下面的代码将为每个dataField提供一个结果对象,并将CSVHeadersAndFieldsindex属性用作它们的header属性。

const result = CSVHeadersAndFields.map(item => item.dataFields.map(field => { return { header: item.index, field } }) );

You can try following approach:

Logic:

  • Loop over data and push data in an array based on parsing logic.
  • In every iteration, you can again loop over obj.dataFields and create object for every field.
  • You can then merge this output array to original output list.

 var data = [ {index:1, headerCSV:"Name", dataFields: ["Name", "Id"] }, {index:2, headerCSV:"Id", dataFields: ["Test", "Test 1"] }, {index:3, headerCSV:"fname", dataFields: ["Test", "Test 1"] }, {index:4, headerCSV:"lname", dataFields: []} ]; var output = data.reduce((acc, obj) => { const header = obj.index; return acc.concat( obj.dataFields.map((field) => ({ header, field}) )) }, []); console.log(output) 

here is the simpler code:

    var CSVHeadersAndFields = [ {index:1, headerCSV:"Name", dataFields: ["Name","Id"]},
     {index:2, headerCSV:"Id", dataFields:["Test","Test 1"]},{index:3, headerCSV:"fname", dataFields:["Test","Test 1"]}, {index:4, headerCSV:"lname", dataFields:[]};

    var headerFieldMappingJSON  = [];

   for(var CSVHeadersAndField of CSVHeadersAndFields ) {
       for(var dataFieldVal of CSVHeadersAndField['dataFields']){
         headerFieldMappingJSON.push({'header': CSVHeadersAndField['index'], 'field': dataFieldVal })
       }
   }

output:

[
  {
    "header": 1,
    "field": "Name"
  },
  {
    "header": 1,
    "field": "Id"
  },
  {
    "header": 2,
    "field": "Test"
  },
  {
    "header": 2,
    "field": "Test 1"
  },
  {
    "header": 3,
    "field": "Test"
  },
  {
    "header": 3,
    "field": "Test 1"
  }
]

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