Thursday, October 5, 2023
 Popular · Latest · Hot · Upcoming
103
rated 0 times [  104] [ 1]  / answers: 1 / hits: 12289  / 7 Years ago, fri, february 17, 2017, 12:00:00

I have an array of objects which is created by pulling data from a csv file. The array looks like the following (when printed).



Array[4]
0:Object
value1:200
value2:95
value3:6395
value4:2
1:Object
2:Object
3:Object


The way I created it is the following.



var strCSV = e.target.result;
var arrCSV = strCSV.match(/[w .]+(?=,?)/g);
var noOfCols = 4;

// To ignore the first row which is header
var hdrRow = arrCSV.splice(0, noOfCols);

var data = [];
while (arrCSV.length > 0) {
var obj = {};
// extract remaining rows one by one
var row = arrCSV.splice(0, noOfCols)
for (var i = 0; i < row.length; i++) {
obj[hdrRow[i]] = row[i].trim();
}
// push row to an array
data.push(obj)
}


So let's say now I want to create another array of objects, with the same data values, but different keys.



var tableData = [
{key1: , key2: , key3: , key4: }];


I've tried different ways to do I haven't been able to do it. For example I tried the following.



for(var i=0; i<data.length; i++){
console.log(i);
tableData[i][key1] = data[i].value1;
}


Or something with a similar form. I created an empty array tableData = [] thinking that creating the elements on the spot would do the trick, but it won't. Is there anyway to do this? I can't just create a object and copy all the elements from the first array one by one as the number of elements in the first array could be anything.


More From » arrays

 Answers
2

Try this:



for(var i=0; i<data.length; i++){
console.log(i);
var obj = { key1: data[i].value1, key2: data[i].value2};
tableData.push(obj);
}

[#22765] Thursday, February 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brendan

Total Points: 426
Total Questions: 110
Total Answers: 94

Location: Western Sahara
Member since Mon, May 3, 2021
2 Years ago
;