如何从指定字符串数组获取对应对象属性(排除指定属性)
bills from Payment Objects) Got it, let's tackle this problem step by step. Here's a practical approach using JavaScript to extract the key-value pairs exactly as you need:
First, let's break down the requirements clearly:
- Parse each path string to access the corresponding object in your data structure
- For payment-level paths (like
payments[0]), extract all key-value pairs except thebillsproperty - For bill-level paths (like
payments[0].bills[0]), extract all key-value pairs from the bill object
Step 1: Helper Function to Parse Path Strings
We'll start with a helper function to convert path strings like payments[0].bills[0] into an array of keys/indexes we can use to traverse the object safely:
function parsePath(path) { // Split the path by dots, then split array index syntax into separate entries return path.split('.').flatMap(part => { const indexMatch = part.match(/^(\w+)\[(\d+)\]$/); if (indexMatch) { return [indexMatch[1], parseInt(indexMatch[2], 10)]; } return [part]; }); }
Step 2: Core Function to Extract Key-Value Pairs
Next, the main function that takes your data object and path array, then returns the filtered key-value pairs:
function extractKeyValuePairs(data, paths) { const extractedPairs = []; paths.forEach(path => { const parsedPath = parsePath(path); let currentObject = data; // Traverse the parsed path to reach the target object for (const keyOrIndex of parsedPath) { currentObject = currentObject[keyOrIndex]; if (!currentObject) break; // Exit early if the path doesn't exist in the data } if (!currentObject) return; // Skip if the path leads to nothing // Check if this is a payment object path (length 2: ['payments', index]) if (parsedPath.length === 2 && parsedPath[0] === 'payments') { // Extract all keys except 'bills' Object.entries(currentObject).forEach(([key, value]) => { if (key !== 'bills') { extractedPairs.push({ sourcePath: path, key, value }); } }); } else { // It's a bill object path—extract all key-value pairs Object.entries(currentObject).forEach(([key, value]) => { extractedPairs.push({ sourcePath: path, key, value }); }); } }); return extractedPairs; }
Step 3: Example Usage
Let's test this with your sample data structure:
// Sample data matching your structure const sampleData = { payments: [ { paymentId: 'PAY-001', totalAmount: 150, currency: 'USD', bills: [ { accountNumber: 'ACC-1001', billAmount: 75 }, { accountNumber: 'ACC-1002', billAmount: 75 } ] }, { paymentId: 'PAY-002', totalAmount: 300, currency: 'EUR', bills: [ { accountNumber: 'ACC-2001', billAmount: 200 }, { accountNumber: 'ACC-2002', billAmount: 100 } ] } ] }; // Your provided path array const targetPaths = ["payments[0]", "payments[0].bills[0]", "payments[1]", "payments[1].bills[0]", "payments[1].bills[1]"]; // Run the extraction const result = extractKeyValuePairs(sampleData, targetPaths); console.log(result);
What the Output Looks Like
The result array will contain entries structured like this:
[ { sourcePath: 'payments[0]', key: 'paymentId', value: 'PAY-001' }, { sourcePath: 'payments[0]', key: 'totalAmount', value: 150 }, { sourcePath: 'payments[0]', key: 'currency', value: 'USD' }, { sourcePath: 'payments[0].bills[0]', key: 'accountNumber', value: 'ACC-1001' }, { sourcePath: 'payments[0].bills[0]', key: 'billAmount', value: 75 }, // ... and so on for all remaining paths ]
This approach ensures you skip the bills property when accessing payment objects, while capturing every key-value pair from bill objects—exactly what you asked for.
内容的提问来源于stack exchange,提问作者JuanmaPérez

