Switch Switch - 2 months ago 6
Javascript Question

Re-structuring an array of objects with Underscore

Is it possible to re-structure the below array

[
{"period":"2016-09-18","mp-demo-1":30},
{"period":"2016-09-18","MP7":20},
{"period":"2016-09-19","mp-demo-1":13},
{"period":"2016-09-19","MP7":33},
{"period":"2016-09-20","mp-demo-1":39},
{"period":"2016-09-20","MP7":29}
]


into

[
{"period":"2016-09-18","mp-demo-1":30,"MP7":20},
{"period":"2016-09-19","mp-demo-1":13,"MP7":33},
{"period":"2016-09-20","mp-demo-1":39,"MP7":29},
]


What I basically need is to remove duplicate entries by the key (period) and add the values containing in those objects in to a single object.

Will this be possible using underscore.js? Or is there another way of doing this using jQuery or any other library.

Answer

You can do this with pure javascript with reduce() and Object.assign()

var data = [
  {"period":"2016-09-18","mp-demo-1":30},
  {"period":"2016-09-18","MP7":20},
  {"period":"2016-09-19","mp-demo-1":13},
  {"period":"2016-09-19","MP7":33},
  {"period":"2016-09-20","mp-demo-1":39},
  {"period":"2016-09-20","MP7":29}
];

var obj = {}
var result = data.reduce(function(r, o) {
  if (!obj[o.period]) {
    obj[o.period] = o;
    r.push(obj[o.period]);
  } else {
    Object.assign(obj[o.period], o);
  }
  return r;
}, []);

console.log(result)

To keep original data you can create clone of object JSON.parse() and JSON.stringify()

var data = [
  {"period":"2016-09-18","mp-demo-1":30},
  {"period":"2016-09-18","MP7":20},
  {"period":"2016-09-19","mp-demo-1":13},
  {"period":"2016-09-19","MP7":33},
  {"period":"2016-09-20","mp-demo-1":39},
  {"period":"2016-09-20","MP7":29}
];


var obj = {}
var result = data.reduce(function(r, o) {
  if (!obj[o.period]) {
    obj[o.period] = JSON.parse(JSON.stringify(o))
    r.push(obj[o.period]);
  } else {
    Object.assign(obj[o.period], o);
  }
  return r;
}, []);

console.log(result);
console.log(data);

Comments