如何用JavaScript拆分包含月度数据的对象数组?
问题分析与解决
原始数据
[ { "KPI": "Productivty [%] - Target", "Area": "Plant", "Jan22": 0.8621397507374327, "Feb22": 0.8605700219733681, "Mrz22": 0.8870898346258058 }, { "KPI": "Productivty [%] - Target", "Area": "Assembly", "Jan22": 0.8817383050990651, "Feb22": 0.8856950523200521, "Mrz22": 0.9267495852228734 }, { "KPI": "Productivty [%] - Target", "Area": "Assembly CYU", "Jan22": 0.8984342053383161, "Feb22": 0.9285678969440421, "Mrz22": 0.9625283644615115 } ]
预期输出
[ { "KPI": "Productivty [%] - Target 0 ", "Area": "Plant", "Month": 0.8621397507374327 }, { "KPI": "Productivty [%] - Target 1 ", "Area": "Plant", "Month": 0.8605700219733681 }, { "KPI": "Productivty [%] - Target 2 ", "Area": "Plant", "Month": 0.8870898346258058 }, { "KPI": "Productivty [%] - Target 0 ", "Area": "Assembly", "Month": 0.8817383050990651 }, { "KPI": "Productivty [%] - Target 1 ", "Area": "Assembly", "Month": 0.8856950523200521 }, { "KPI": "Productivty [%] - Target 2 ", "Area": "Assembly", "Month": 0.9267495852228734 }, { "KPI": "Productivty [%] - Target 0 ", "Area": "Assembly CYU", "Month": 0.8984342053383161 }, { "KPI": "Productivty [%] - Target 1 ", "Area": "Assembly CYU", "Month": 0.9285678969440421 }, { "KPI": "Productivty [%] - Target 2 ", "Area": "Assembly CYU", "Month":0.9625283644615115 } ]
现有代码问题
- 变量定义错误:
obj未用方括号包裹成数组,直接用逗号分隔多个对象,导致JavaScript仅识别第一个对象,后续对象被忽略。 - 未遍历数组元素:仅调用
fn(obj)处理单个对象,未循环处理数组中所有元素。 - 字段名错误:新对象使用
Bereich字段,与预期输出的Area字段不匹配。
修改后的代码
// 正确定义原始数据为数组 const originalData = [ { "KPI": "Productivty [%] - Target", "Area": "Plant", "Jan22": 0.8621397507374327, "Feb22": 0.8605700219733681, "Mrz22": 0.8870898346258058 }, { "KPI": "Productivty [%] - Target", "Area": "Assembly", "Jan22": 0.8817383050990651, "Feb22": 0.8856950523200521, "Mrz22": 0.9267495852228734 }, { "KPI": "Productivty [%] - Target", "Area": "Assembly CYU", "Jan22": 0.8984342053383161, "Feb22": 0.9285678969440421, "Mrz22": 0.9625283644615115 } ]; const Ausgabe2 = []; // 处理单个对象的函数,同时在map中添加索引拼接KPI const processItem = ({ KPI, Area, ...rest }) => Object.values(rest).map((Month, index) => ({ KPI: `${KPI} ${index}`, Area, Month })); // 遍历原始数组,处理每个对象后合并结果 originalData.forEach(item => { const processed = processItem(item); Ausgabe2.push(...processed); }); console.log(Ausgabe2);
代码说明
- 将原始数据正确定义为数组
originalData,确保所有对象可被遍历处理。 - 优化
processItem函数,在map时直接获取索引拼接KPI字符串,同时修正字段名为Area。 - 使用
forEach遍历原始数组,调用处理函数后用扩展运算符...将处理后的多个对象批量添加到结果数组中。
内容的提问来源于stack exchange,提问作者WhosWho
相关产品推荐
相关产品推荐

