如何使用JavaScript遍历JSON数组并根据responseCode筛选结果?
Traversing Nested JSON to Fetch Results by
responseCode in JavaScript Got it, let's walk through how to work with this nested JSON structure and extract results based on the responseCode field. First, let's break down the structure to understand what we're dealing with:
obj.resultis a 2-dimensional array (an array of arrays)- Each inner array contains a single object (like
{ "PARAM 1": [...] }) - Each of those objects has a key (e.g., "PARAM 1") that maps to an array of error objects, each with the
responseCodewe care about.
Step 1: Flatten the Nested Structure
First, we'll flatten the nested arrays and objects to get a clean list of all error objects. This makes filtering later much easier.
Here's a straightforward approach using nested forEach loops:
var obj = { "result": [ [ { "PARAM 1": [ { "field": "firstName", "message": "Parameter is required", "moreInfo": "https://google.com", "responseCode": "-1015" }, { "field": "lastName", "message": "Parameter is required", "moreInfo": "https://google.com", "responseCode": "-1015" } ] } ], [ { "PARAM 2": [ { "field": "ZipCode", "message": "Invalid Code", "moreInfo": "https://google.com", "responseCode": "-1020" } ] } ] ] }; const allErrors = []; // Traverse the outer result array obj.result.forEach(outerArr => { // Each outerArr element is an array with one param object outerArr.forEach(paramObj => { // Extract the error array from the param object (using Object.values to get the value of keys like "PARAM 1") Object.values(paramObj).forEach(errorArr => { // Add each error object to our allErrors list errorArr.forEach(error => allErrors.push(error)); }); }); }); console.log(allErrors); // Logs all 3 error objects
If you prefer a more concise approach, you can use flatMap and flat to flatten the structure in a single chain:
const allErrors = obj.result .flat() // Convert the 2D outer array to 1D .flatMap(paramObj => Object.values(paramObj).flat()) // Extract error arrays and flatten .flat(); // Flatten the final error arrays into individual objects
Step 2: Filter by responseCode
Once we have a flat list of errors, we can easily filter them by responseCode using the filter method:
// Function to get all errors matching a specific responseCode function getErrorsByCode(targetCode) { return allErrors.filter(error => error.responseCode === targetCode); } // Example usage: const requiredParamErrors = getErrorsByCode("-1015"); console.log(requiredParamErrors); // Returns the firstName and lastName error objects const invalidZipErrors = getErrorsByCode("-1020"); console.log(invalidZipErrors); // Returns the ZipCode error object
Quick Notes:
- Notice that
responseCodeis a string (e.g.,"-1015"), so make sure your target code matches the type when comparing. If you need numeric codes, convert both to numbers usingparseInt()orNumber(). - If you only need the first error matching the code, use
findinstead offilter(it returns a single object instead of an array).
内容的提问来源于stack exchange,提问作者raf
相关产品推荐
相关产品推荐

