"Cannot find property name of undefined" while creating a nested data

Viewed 87

I'm trying to create a nested tree object using an existing data-set. The original data-set is :

var raw_data = [
["A1", "B1", "C1", 1],
["A1", "B1", "C2", 2],
["A1", "B2", "C1", 3],
["A1", "B2", "C1", 4],
["A1", "B2", "C2", 5],
["A1", "B2", "C2", 6],
["A2", "B1", "C1", 7],
["A2", "B1", "C1", 8],
["A2", "B1", "C2", 9],
["A2", "B1", "C2", 10],
["A2", "B2", "C1", 11],
["A2", "B2", "C1", 12],
["A2", "B2", "C2", 13],
["A2", "B2", "C2", 14]
];

I want my final data to look like this :

{'A1': 
  {'B1': {'C2': 2, 'C1': 1}, 
   'B2': {'C2': 6, 'C1': 4}
  }, 
 'A2': 
  {'B1': {'C2': 10, 'C1': 8}, 
   'B2': {'C2': 14, 'C1': 12}
  }
}

Here's my progress so far.

var obj = {};

for(i = 0; i< raw_data.length; i++) { 
  var [x,y,z,value] = raw_data[i];
  obj[x][y][z] = value;  
}

I loop through the data and run the property values recursively on an empty data. For example: In 1st iteration I set obj['A1']['B1']['C1'] = 1. However, this causes issue because the first recursion (obj['A1']) will return undefined so the following error :

"TypeError: Cannot set property 'B1' of undefined

To resolve this, instead of var obj = {}, I tried to use proxy object in ES6 like this:

var obj = new Proxy({}, { 
    get: function(target, name) {
        if (!(name in target)) {
            console.log("Non-existant property '" + name + "'");
            var val = target[name] = typeof(target);  //Returning reference to already created object
            return val;  
        }
    }
}); 

However, now the following error is returned: "TypeError: Cannot set property 'C1' of undefined

What am I doing wrong here?

3 Answers

You could use a dynamic approach and reduce the given keys until the last element and take this as accessor for assigning the value.

Inside of getting the right inner object, a default object is assigned to a property, if the object does not exists.

function setValue(object, path, value) {
    var last = path.pop();
    path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
    return object;
}

var raw_data = [["A1", "B1", "C1", 1], ["A1", "B1", "C1", 2], ["A1", "B1", "C2", 3], ["A1", "B2", "C1", 4], ["A1", "B2", "C1", 5], ["A1", "B2", "C2", 6], ["A1", "B2", "C2", 7], ["A2", "B1", "C1", 8], ["A2", "B1", "C1", 9], ["A2", "B1", "C2", 10], ["A2", "B1", "C2", 11], ["A2", "B2", "C1", 12], ["A2", "B2", "C1", 13], ["A2", "B2", "C2", 14], ["A2", "B2", "C2", 15]],
    object = raw_data.reduce((r, a) => setValue(r, a.slice(0, -1), a[a.length - 1]), {});

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

With ES6, you could do

for(i = 0; i< raw_data.length; i++) { 
  var [x,y,z,value] = raw_data[i];

  obj[x] && obj[x][y] ? obj[x][y][z] = value : obj[x] ? obj[x][y] = {[z] : value} : obj[x] = {[y] : {[z] : value}};
}

Thanks to ComputedPropertyName (see https://stackoverflow.com/a/2274327/3057341)

Here is my code solution to your problem. I iterated through each element in the array of arrays and populate the object following the nesting structure.

const raw_data = [
    ["A1", "B1", "C1", 1],
    ["A1", "B1", "C2", 2],
    ["A1", "B2", "C1", 3],
    ["A1", "B2", "C1", 4],
    ["A1", "B2", "C2", 5],
    ["A1", "B2", "C2", 6],
    ["A2", "B1", "C1", 7],
    ["A2", "B1", "C1", 8],
    ["A2", "B1", "C2", 9],
    ["A2", "B1", "C2", 10],
    ["A2", "B2", "C1", 11],
    ["A2", "B2", "C1", 12],
    ["A2", "B2", "C2", 13],
    ["A2", "B2", "C2", 14]
    ];

let obj = {};
raw_data.forEach(element => {
    for(let i=0; i<4; i++){
        let first_elem = element[0];
        let second_elem = element[1];
        let third_elem = element[2];
        let fourth_elem = element[3];
        switch(i){
            case 0:
                if(!(first_elem in obj)){
                    obj[first_elem] = {};
                }
            break;
            case 1:
                if(!(second_elem in obj[first_elem])){
                    obj[first_elem][second_elem] = {};
                }
            break;
            case 2:
                if(!(third_elem in obj[first_elem][second_elem])){
                    obj[first_elem][second_elem][third_elem] = null;
                }
            break;
            case 3:
                if(fourth_elem != obj[first_elem][second_elem][third_elem]){
                    obj[first_elem][second_elem][third_elem] = fourth_elem;
                }
            break;
        }
    }  
});    
console.log(obj);
Related