javascript - Efficient way to convert an array into an object where each key is a value of a member of the array -
suppose have data:
var obj = [ { type: 1, value: "abc" }, { type: 2, value: "abcde" }, { type: 1, value: "fghez" } ];
is there efficient , elegant way in javascript transform object follows?
var sortedbytype = { 1: [ "abc", "fghez" ], 2: [ "abcde" ] }
obviously can loop through every element in obj
, read type
property , add value
new object, assembling result 1 one, below. kind of seems strange, long, inefficient , not elegant.
var sortedbytype = {}; (var = 0; < obj.length; i++) { var type = obj[i].type; if (!sortedbytype[type]) { sortedbytype[type] = []; } sortedbytype[type].push(obj[i].value); }
you use array#reduce
object accumulator.
var array = [{ type: 1, value: "abc" }, { type: 2, value: "abcde" }, { type: 1, value: "fghez" }], result = array.reduce(function (r, a) { if (!r[a.type]) { r[a.type] = []; } r[a.type].push(a.value); return r; }, object.create(null)); console.log(result);
Comments
Post a Comment