How Do I Pivot An Array Of Objects in JavaScript? -
i have array of object need convert table (kind of pivoting data). saying need array of objects unique titles have nested arrays of object pairs of values. please take , achiving need? please see original , desired array below:
original array:
[ {title: "title1", value1: "value1", value2: "value2"}, {title: "title2", value1: "value1", value2: "value2"}, {title: "title1", value1: "value1", value2: "value2"}, {title: "title3", value1: "value1", value2: "value2"}, {title: "title2", value1: "value1", value2: "value2"}, {title: "title1", value1: "value1", value2: "value2"}, {title: "title3", value1: "value1", value2: "value2"}, {title: "title1", value1: "value1", value2: "value2"}, ]
desired result:
[ {title: "title1", values: [{value1: "value1"}, {value2: "value2"}]}, {title: "title2", values: [{value1: "value1"}, {value2: "value2"}]}, {title: "title3", values: [{value1: "value1"}, {value2: "value2"}]}, ]
thanks if advance suggestions.
you use hash table grouping thisarg
array#foreach
.
var data = [{ title: "title1", value1: "value1", value2: "value2" }, { title: "title2", value1: "value1", value2: "value2" }, { title: "title1", value1: "value1", value2: "value2" }, { title: "title3", value1: "value1", value2: "value2" }, { title: "title2", value1: "value1", value2: "value2" }, { title: "title1", value1: "value1", value2: "value2" }, { title: "title3", value1: "value1", value2: "value2" }, { title: "title1", value1: "value1", value2: "value2" }], grouped = []; data.foreach(function (a) { // check if title not in hash table if (!this[a.title]) { // if not, create new object title , values array // , assign title hash hash table this[a.title] = { title: a.title, values: [] }; // add new object result set, grouped.push(this[a.title]); } // create new object other values , push // array of object of hash table this[a.title].values.push({ value1: a.value1, value2: a.value2 }); }, object.create(null)); // object.create creates empty object without prototypes console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comments
Post a Comment