I have a question regarding the use of for loops in JavaScript or utilizing Angular to output the resulting object list.
Here is an example of an object list:
var alist = [];
alist = [
{ 'code': 1000, 'type': 'C', 'a': 4, 'b': null, 'c': null },
{ 'code': 1000, 'type': 'C', 'a': null, 'b': null, 'c': 6 },
{ 'code': 1500, 'type': 'O', 'a': null, 'b': null, 'c': 8 },
{ 'code': 1500, 'type': 'O', 'a': null, 'b': 8, 'c': null },
{ 'code': 1000, 'type': 'O', 'a': 7, 'b': null, 'c': null },
{ 'code': 1000, 'type': 'C', 'a': null, 'b': 7, 'c': null },
{ 'code': 2000, 'type': 'C', 'a': 4, 'b': null, 'c': null },
{ 'code': 2000, 'type': 'C', 'a': null, 'b': 6, 'c': 12 },
{ 'code': 3000, 'type': 'C', 'a': 1, 'b': null, 'c': 12 },
{ 'code': 3000, 'type': 'C', 'a': null, 'b': 6, 'c': null }
];
The desired result is to combine objects with the same code and type, while summing up the values of a, b, and c. Here is the expected result:
var resultList = [];
resultList = [
{ 'code': 1000, 'type': 'C', 'a': 4, 'b': 7, 'c': 6 },
{ 'code': 1500, 'type': 'O', 'a': null, 'b': 8, 'c': 8 },
{ 'code': 1000, 'type': 'O', 'a': 7, 'b': null, 'c': null },
{ 'code': 2000, 'type': 'C', 'a': 4, 'b': 6, 'c': 12 },
{ 'code': 3000, 'type': 'C', 'a': 1, 'b': 6, 'c': 12 },
];
Key points to consider:
- The 'code' value is dynamic and should not be hardcoded (e.g., 1000, 1500, 2000).
- Each unique 'code' only contains one type, such as code 1000 only having type C.
Is it possible to achieve this desired output?
I have attempted to work on this in this jsfiddle, but I have yet to successfully produce the 'resultList'.