简体   繁体   中英

How to Combine Same key JavaScript Object to one Array Dynamically

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: '%'
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM