[英]how to combine objects in an array that have the same key in javascript?
[英]How to Combine Same key JavaScript Object to one Array Dynamically
如何在 JavaScript/Nodejs 中动态地将相同的键 JavaScript Object 组合到一个数组中,并生成给定的输入到预期的 output,
请帮我解决这个问题。 那真的很有帮助。
例子 -
[
{
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 }
}
]
预计 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: '%'
}
您可以迭代输入数据的键。 然后,如果您的结果中已经存在该键,则 append 新值,否则使用结果中的第一个值创建一个数组。
这是一个工作演示:
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.