如何从嵌套对象数组中提取各项目current_result的字段值并整理为对应数组?
Fixing Your Project Result Extraction Code
Let's break down what was going wrong with your original code and fix it step by step:
Key Issues in Your Code:
forEachdoesn't return a value: You're assigning the result ofdata.forEach()toalteredResponse, butforEachalways returnsundefined—so this variable won't hold your desired arrays.- Incorrect
reducetarget: You're callingreduceonprj(each vertical object indata), but you should be reducing overprj.projects(the array of projects inside each vertical). - Wrong destructuring: You're trying to extract
countfrom each project, but the property you need iscurrent_result.
Corrected Code
Here's a revised version that will give you the exact arrays you're looking for:
let data = [ { vertical_name: "CORE", projects: [ { name: "Alpha", id: 187, current_result: { success: 0, failure: 0, skip: 0, untested: 100 } } ] }, { vertical_name: "release", projects: [ { name: "Beta", id: 27, current_result: { success: 50, failure: 20, skip: 36, untested: 0 } }, { name: "Charlie", id: 47, current_result: { success: 37, failure: 25, skip: 40, untested: 0 } } ] } ]; // Initialize our result object with empty arrays const result = data.reduce((acc, vertical) => { // Loop through each project in the current vertical vertical.projects.forEach(project => { // Extract the values from current_result const { success, failure, skip, untested } = project.current_result; // Push each value to its respective array (fallback to 0 if undefined) acc.success.push(success || 0); acc.failure.push(failure || 0); acc.skip.push(skip || 0); acc.untested.push(untested || 0); }); return acc; }, { success: [], failure: [], skip: [], untested: [] }); console.log(result.success); // [0, 50, 37] console.log(result.failure); // [0, 20, 25] console.log(result.skip); // [0, 36, 40] console.log(result.untested); // [100, 0, 0]
How This Works:
reduceondata: We usereduceto build our result object starting with empty arrays for each metric.- Iterate over projects: For each vertical, we loop through its
projectsarray. - Extract and push values: For each project, we destructure the
current_resultproperties and push them into the corresponding arrays in our accumulator. - Fallback values: The
|| 0ensures that if a property is missing, we add0instead ofundefined.
Alternative (Using Nested reduce)
If you prefer to use reduce for both levels instead of forEach, here's another version:
const result = data.reduce((acc, vertical) => { return vertical.projects.reduce((innerAcc, project) => { const { success, failure, skip, untested } = project.current_result; innerAcc.success.push(success || 0); innerAcc.failure.push(failure || 0); innerAcc.skip.push(skip || 0); innerAcc.untested.push(untested || 0); return innerAcc; }, acc); }, { success: [], failure: [], skip: [], untested: [] });
Both approaches will produce the exact output you're expecting.
内容的提问来源于stack exchange,提问作者Aren Trot
相关产品推荐
相关产品推荐

