Skip to content Skip to sidebar Skip to footer

Merge Json Array Date Based

I can't find a solution for this : i want to group json array based on one column (date) and sort it with Javascript / Jquery ? : I have been trying finding a solution but i can't

Solution 1:

You can first use sort() method to sort elements by date and then you can use forEach() to group elements by date.

var data = [{"date":"2010-01-01","price":30},{"date":"2010-02-01","price":40},{"date":"2010-03-01","price":50},{"date":"2010-01-01","price2":45},{"date":"2010-05-01","price2":40},{"date":"2010-10-01","price2":50}]
data.sort((a, b) =>newDate(a.date) - newDate(b.date))

var result = []
data.forEach(function(e) {
  if(!this[e.date]) {
    this[e.date] = {date: e.date, price: null, price2: null}
    result.push(this[e.date])
  }
  this[e.date] = Object.assign(this[e.date], e)
})

console.log(JSON.stringify(result, 0, 4))

Solution 2:

You can try Array.reduce and Array.map to loop and Object.assign to merge

var data = [{"date":"2010-01-01","price":30},{"date":"2010-02-01","price":40},{"date":"2010-03-01","price":50},{"date":"2010-01-01","price2":45},{"date":"2010-05-01","price2":40},{"date":"2010-10-01","price2":50}]

var result = data.reduce((p, c) => 
  (p[c.date] = Object.assign({},{price: null, price2:null}, p[c.date], c)) && p
  , {});

var final = Object.keys(result).map(x=>result[x])

console.log(final)

Solution 3:

Using Array.reduce() and Array.find()

var prices = [{"date":"2010-01-01","price":30},{"date":"2010-02-01","price":40},{"date":"2010-03-01","price":50},{"date":"2010-01-01","price2":45},{"date":"2010-05-01","price2":40},{"date":"2010-10-01","price2":50}];

var prices2 = prices.reduce(function(acc, val) {
  var dateElement = acc.find(function(element) {
    return val.date === element.date;
  });

  if (!dateElement) {
    dateElement = {
      date: val.date,
      price: null,
      price2: null,
    };
    acc.push(dateElement);
  }
  dateElement.price = dateElement.price || val.price;
  dateElement.price2 = dateElement.price2 || val.price2;

  return acc;
}, []);

console.log(prices2);

Solution 4:

You could use an object as reference to the same date.

var data = [{ date: "2010-01-01", price: 30 }, { date: "2010-02-01", price: 40 }, { date: "2010-03-01", price: 50 }, { date: "2010-01-01", price2: 45 }, { date: "2010-05-01", price2: 40 }, { date: "2010-10-01", price2: 50 }],
    grouped = [];

data.forEach(function (hash) {
    returnfunction (o) {
        if (!hash[o.date]) {
            hash[o.date] = { date: o.date, price: null, price2: null };
            grouped.push(hash[o.date]);
        }
        Object.keys(o).forEach(function (k) {
            if (k === 'date') {
                return;
            }
            hash[o.date][k] = o[k];
        });
    };
}(Object.create(null)));

console.log(grouped);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Post a Comment for "Merge Json Array Date Based"