Guy Messika Guy Messika - 2 months ago 8
Javascript Question

how to calculate new data from objects in javascript

I have the following data:

[ {
"names" : [ "a3","printed","black" ],
"value" : 15
}, {
"names" : [ "a3","copied","black" ],
"value" : 87
}, {
"names" : [ "a3","printed","color","full" ],
"value" : 37
}, {
"names" : [ "a3","copied","color","single" ],
"value" : 0
}, {
"names" : [ "a3","copied","color","full" ],
"value" : 44
}, {
"names" : [ "a3","scanned" ],
"value" : 288
}, {
"names" : [ "total" ],
"value" : 242142
}, {
"names" : [ "scanned" ],
"value" : 67411
}, {
"names" : [ "copied","black" ],
"value" : 79997
}, {
"names" : [ "copied","full","color" ],
"value" : 809
}, {
"names" : [ "copied","single","color" ],
"value" : 0
}, {
"names" : [ "printed","two","color" ],
"value" : 0
}, {
"names" : [ "printed","black" ],
"value" : 120665
}, {
"names" : [ "printed","full","color" ],
"value" : 40657
} ]


I tried to create some structure to organize the data in a way I can see relations between objects and calculate new objects.
basically what I want is to be able to calculate missing data.
So for example I know these relations:

{
"colors" : {
"black" : "",
"color" : [ "full", "two", "single" ]
},
"functions" : {
"scanned" : "",
"total" : [ "printed", "copied", "faxed" ]
},
"papers" : {
"a3" : ""
}
}


Based on this I would like to get the following:

{
"a3" : 183,
"color" : 41466,
"black" : 200662,
"copied" : 80806,
"printed" : 161322
}


I know it by taking into consideration the following:
a3 total is only composed of the functions printed, copied and faxed so for example the a3 scanned value is not inside that calculation for the value of a3 total.

but I can't think of any idea how to do it using JavaScript.
can anybody points me in the right direction?

Answer

Do you need to calculate value for each of names? If yes, then try

var output = {};
for (var i in data) {
    for (var j in data[i].names) {
        var mark = data[i].names[j];
        output[mark] = (output[mark] || 0) + data[i].value;
    }
} 

https://jsfiddle.net/chukanov/0kctjwyv/