0

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

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.