Folpe Folpe - 6 months ago 9
Javascript Question

Generate object from array list javascript

How would one take a JavaScript array such as:

var listArray = [
['a', 'blue', 52],
['a', 'green', 27],
['a', 'yellow', 36],
['b', 'red', 99],
['b', 'blue', 11]
];


and merge duplicate in a new objecct. In order to get something like this:

var newObject = {
'a': {
'name': 'a',
'colors': {
'blue': {
'name': 'blue',
'value': 52
},
'green': {
'name': 'green',
'value': 27
}
}
},
'b': {
'name': 'b',
'colors': {
'red': {
'name': 'red',
'value': 99
},
'blue': {
'name': 'blue',
'value': 11
}
}
}
}


What I've been try so far but still not working:

var newObject = {};
var colors = {}
for (var item in listArray ) {
newObject[listArray[item][0]] = {
'name': myViewData[item][0]
};
newObject[listArray[item][0]].colors = colors[listArray[item][1]] = {'name' : listArray[item][1], 'value' : listArray[item][2]};
}
}

Answer

Try this:

var newObject = { };

for (var i = 0; i < listArray.length; i += 1) {
    var triple = listArray[i];

    if (!(triple[0] in newObject)) {
        newObject[triple[0]] = {
            name: triple[0],
            colors: {}
        };
    }

    newObject[triple[0]].colors[triple[1]] = {
        name: triple[1],
        value: triple[2]
    };
}