I found this solution for the kind of problem I'm trying to solve here
The only difference is that my array of object has more than 2 elements and the result wanted is similar to the solution but with all the elements
{
"group": "one",
"color": ["red", "green", "black"],
"size": ["big"],
"date": ["11/08/2018"]
}
So I've been repeating the .map()
to get all my values to show but I feel that I shouldn't ...
Can someone please help me with and simpler and better option?
var db = [{"Record":{"id":"26","cost_center":"15073 DC1 M8 - Filmatic","batch_no":"367746","item_code":"12583","description":"LF Fruited Guava (2x6)x15"}},{"Record":{"id":"29","cost_center":"15073 DC1 M8 - Filmatic","batch_no":"367749","item_code":"12583","description":"LF Fruited Guava (2x6)x15"}},{"Record":{"id":"36","cost_center":"15093 DC1 M10 - CornerPot Machi","batch_no":"367756","item_code":"12256","description":"PROMO CP LF SaltedCar w H"}}];
var myArray = [];
for (var i in db) {
if (db.hasOwnProperty(i)) {
myArray.push(db[i].Record);
}
}
var res = myArray.reduce(function(res, elem) {
if (res.indexOf(elem.cost_center) === -1) {
res.push(elem.cost_center);
}
return res;
}, []).map(function(machine) {
return {
cost_center: machine,
batch_no: myArray.filter(function(_el) {
return _el.cost_center === machine;
}).map(function(_el) { return _el.batch_no; }),
item_code: myArray.filter(function(_el) {
return _el.cost_center === machine;
}).map(function(_el) { return _el.item_code; }),
description: myArray.filter(function(_el) {
return _el.cost_center === machine;
}).map(function(_el) { return _el.description; })
}
});
console.log(res);