Elijah Niko
Elijah Niko

Reputation: 25

JavaScript: take properties from multiple objects and assign to one

So im working with an array of objects that requires data from multiple objects to be put into one dependant on the date within those objects.

The starting object looks like this:

[
  {
    "LOCATION":17,
    "Stock_In_Area":39.0709838867,
    "DATE_DT":"2021-03-07",
  },
  {
    "LOCATION":17,
    "Stock_In_Area":41.8843955994,
    "DATE_DT":"2021-03-14",
  },
  {
    "LOCATION":612,
    "Stock_In_Area":8.4867076874,
    "DATE_DT":"2021-03-07",
  },
  {
    "LOCATION":612,
    "Stock_In_Area":9.2035646439,
    "DATE_DT":"2021-03-14",
  },
];

and im trying to get something like this:

{
    "17":39.0709838867,
    "612":8.4867076874,
    "date":"2021-03-07",
  },
  {
    "17":41.8843955994,
    "612":9.2035646439,
    "date":2021-03-14
  },

So the object would be

{
 [location]: stock_in_area
 date: DATE_DT
}

where the two locations have the same date value

Upvotes: 0

Views: 72

Answers (1)

Rayon
Rayon

Reputation: 36609

I would have maintained a hash kind of variable in memory and compared each item from array wrt to the value present in the hash.

let ip = [{
    "LOCATION": 17,
    "Stock_In_Area": 39.0709838867,
    "DATE_DT": "2021-03-07",
  },
  {
    "LOCATION": 17,
    "Stock_In_Area": 41.8843955994,
    "DATE_DT": "2021-03-14",
  },
  {
    "LOCATION": 612,
    "Stock_In_Area": 8.4867076874,
    "DATE_DT": "2021-03-07",
  },
  {
    "LOCATION": 612,
    "Stock_In_Area": 9.2035646439,
    "DATE_DT": "2021-03-14",
  },
];
const _enum = {};
const op = [];
for (let i = 0; i < ip.length; i++) {
  let _k = ip[i].DATE_DT;
  if (!_enum[_k]) {
    _enum[_k] = _k;
    op.push({
      date: _k,
      [ip[i].LOCATION]: ip[i].Stock_In_Area
    });
  } else {
    const found = op.find(el => el.date === _k);
    found[ip[i].LOCATION] = ip[i].Stock_In_Area;
  }
}
console.log(op);

Upvotes: 1

Related Questions