0

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: '%'
    }
4
  • What have you tried so far? Commented Aug 29, 2022 at 16:18
  • Hi @Lissy93 I did it with creating nth different arrays and iterate it and push it into the created arrays, but this solution is very weird and solution should be dynamic in nature. so seeking for help because I am not getting any solutions. Commented Aug 29, 2022 at 16:25
  • 1
    Put your attempt in your question, please. It doesn't belong down here. See How to Ask.
    – isherwood
    Commented Aug 29, 2022 at 16:26
  • 1
    No worries, thanks for explaining. I've added a solution as an answer. You can modify it to your liking if the structure of your input data is different. If it doesn't make sense let me know and I can explain further, otherwise if it helps, don't forget to accept one of the answers. Commented Aug 29, 2022 at 16:27

1 Answer 1

1

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

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.