Home > Software engineering >  How to Combine Same key JavaScript Object to one Array Dynamically
How to Combine Same key JavaScript Object to one Array Dynamically

Time:08-30

How to Combine Same key JavaScript Object to one Array Dynamically in JavaScript/Nodejs and Produce given Input to expected output,

Please do help me on this. that would be really helpful.

Example -

[
  {
    1: { date: 1638334800, value: 0 },
    2: { date: 1638334800, value: 19.71 }
    nth: { date: 1638334800, value: 19.71 }
  },
  {
    1: { date: 1638334900, value: 0 },
    2: { date: 1638334800, value: 23.77 }
    nth: { date: 1638334800, value: 29.71 }
  }
]

Expected Output -

    1: {
      timeSeriesData: [
        {
          date: 1638334800,
          value: 0,
        },
        {
          date: 1638334900,
          value: 0,
        } 
      ], units: '%'
    },
    2: {
      timeSeriesData: [
        {
          date: 1638334800,
          value: 19.71,
        },
        {
          date: 1638334800,
          value: 19.71,
        }
      ], units: '%'
    },
   nth: {
      timeSeriesData: [
        {
          date: 1638334800,
          value: 19.71,
        },
        {
          date: 1638334800,
          value: 29.71,
        }
      ], units: '%'
    }

CodePudding user response:

You can just iterate over your input data's keys. Then if the key already exists in your results you append the new value, otherwise create an array with the first value within your results.

Here's a working demo:

const sample = [
  {
    1: { date: 1638334800, value: 0 },
    2: { date: 1638334800, value: 19.71 },
    nth: { date: 1638334800, value: 19.71 }
  },
  {
    1: { date: 1638334800, value: 0 },
    2: { date: 1638334800, value: 23.77 },
    nth: { date: 1638334800, value: 19.71 }
  }
];

const generateOutput = (inputData) => {
  const results = {};
  inputData.forEach((dataSet) => {
    Object.keys(dataSet).forEach((key) => {
      if (results[key]) {
        results[key].push(dataSet[key]);
      } else {
        results[key] = [dataSet[key]];
      }
    });
  });
  return results;
}

console.log(generateOutput(sample));

  • Related