George George - 5 months ago 11
Javascript Question

Cannot set property '01' of undefined

I have this code:

var _ = require('underscore');

var myObj = [

{'name': 'Mike', 'number' : 'b1' , 'level' : 0 },
{'name': 'Tom', 'number' : 'b2' , 'level' : 0 }
];

var result = _.map(myObj, _.invert);


Now, the result is:

[ { '0': 'level', Mike: 'name', b1: 'number' },
{ '0': 'level', Tom: 'name', b2: 'number' } ]


Ok, until here.

Then, I am adding to the result some parts and trying to fill them:

result = result,
parts = {'levels': {}, 'names': {}, 'numbers': {}};

result.forEach(function(obj,i){

Object.keys(obj).forEach(function(k) {

parts[k +"s"][k +(i+1)] = obj[k];
});
});


but I am receiving :

TypeError: Cannot set property '01' of undefined


at the
parts[k +"s"][k +(i+1)] = obj[k];


Just note ,that if I don't use the
invert
, code runs without problems.

Answer

You might want to change this line:

result.forEach(function(obj,i){
    Object.keys(obj).forEach(function(k) {
        parts[k +"s"][k +(i+1)] = obj[k];
    });
});

To this:

result.forEach(function(obj, i){
    Object.keys(obj).forEach(function(k) { 
        let box = parts[obj[k] + 's'][k];
        if(box) {
            if(Array.isArray(box)) {
                box.push(obj[k] + (i + 1));
            } else {
                parts[obj[k] + 's'][k] = [box, parts[obj[k] + 's'][k].slice(0, -1) + (i + 1)];
            }
            return;
        }

        parts[obj[k] + 's'][k] = obj[k] + (i + 1);
    });
});