[英]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,如何在 JavaScript/Nodejs 中动态地将相同的键 JavaScript Object 组合到一个数组中,并生成给定的输入到预期的 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 -预计 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.然后,如果您的结果中已经存在该键,则 append 新值,否则使用结果中的第一个值创建一个数组。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.