FXAMN FXAMN - 2 months ago 9
Javascript Question

Construct array based on key & values of object

I'm trying to create a code that will receive inputs like this:

{
"11": {
"08/2011": 1
},
"12": {
"08/2011": 2
},
"13": {
"08/2011": 3
}
}


And will output a array like this:

Excel => [
[ "" , "11" , "12" , "13" ], <- headers
[ "08/2011" , 1 , 2 , 3 ] <- first line
]


The goal here is pass the output to
node-xlsx
in order to create a excel spreadsheet.

I was able to create a mockup:



let headers = ['', ];
let data = [headers];
let body = [];

let papas = {
"11": {
"08/2011": 1
},
"12": {
"08/2011": 2
},
"13": {
"08/2011": 3
}
};

for (let cnpjs in papas) {
headers.push(cnpjs);
}

let x = {};

for (let cnpj in papas) {
Object.keys(papas[cnpj]).forEach((lasanha, index) => {
if (typeof x[lasanha] !== 'number') {
x[lasanha] = index;
data.push(body);
body.push(lasanha);
} else {
lasanha = lasanha;
}
body.push(papas[cnpj][lasanha]);
});
}

document.body.innerHTML = JSON.stringify(data, null, 4);





The problem is, inputs like this:

{
"11": {
"08/2011": 1
"09/2011": 1
},
"12": {
"08/2011": 2
},
"13": {
"08/2011": 3
}
}


Will mess the logic, outputting things like:

[
[ "" , "11" , "12" , "13" ],
[ "08/2011" , 1 , "09/2011" , 1 , 2, 3 ],
[ "09/2011" , 1 , "09/2011" , 1 , 2, 3 ] ]


When it should:

[
[ "" , "11" , "12" , "13" ],
[ "08/2011" , 1 , 2 , 3 ],
[ "09/2011" , 1 ]
]


Any help would be appreciated.
Thanks.




Update:

Is not it, but it comes closer ... when I have input like this:

{
"11": {
"08/2011": 1,
"09/2011": 1
},
"12": {
"08/2011": 2,
"10/2011": 1
},
"13": {
"08/2011": 3
}
}


The outputs should be:

[ [ '' , '11' , '12' , '13' ],
[ '08/2011' , 1 , 2 , 3 ],
[ '09/2011' , 1 ],
[ '10/2011' , , 1 ] ]


The 10/2011 belongs to 12 in this case

Answer

You can do this with Object.keys() and two forEach() loops. Note: that refers to this in first loop which is object as optional thisArg parameter.

var input = {
  "11": {
    "08/2011": 1,
    "09/2011": 1
  },
  "12": {
    "08/2011": 2,
    "10/2011": 1
  },
  "13": {
    "08/2011": 3
  }
}

var result = [];
Object.keys(input).forEach(function(k, i) {
  (i == 0) ? result.push(['', k]): result[0].push(k);
  var that = this;
  Object.keys(input[k]).forEach(function(e) {
    if (!that[e]) {
      that[e] = [e];
      result.push(that[e]);
    }
    that[e][i + 1] = input[k][e];
  })
}, {})

console.log(result)

Comments