如何实现支持复杂对象与数组解析的JavaScript自定义解析函数
Got it, let's get that parse function working with array paths like data.interested[1] or even nested ones like a.data.name[0][0].name[0]. The main issue with your current code is that it only splits paths on dots, so it treats interested[1] as a single property name instead of recognizing [1] as an array index.
Here's a revised version of the function that handles both dot-separated properties and array indices:
var a = {data:{info:{name:'mina'},interested: ['programming','makeup']}} function parse(x, y) { // Normalize array indices to dot-separated segments (e.g., "interested[1]" → "interested.1") const normalizedPath = y.replace(/\[(\d+)\]/g, '.$1'); // Split into path segments and filter out empty strings (for edge cases like "[0].name") const pathSegments = normalizedPath.split('.').filter(segment => segment.length > 0); let current = x; for (const segment of pathSegments) { // If current value or the next segment is undefined, set to false (matches original behavior) if (current === undefined || current[segment] === undefined) { current = false; break; } current = current[segment]; } // Only return the value if it's truthy (matches original function's return logic) return current ? current : undefined; }
Testing It Out
Let's verify with your examples and some more complex cases:
parse(a,'data.info.name') // Returns 'mina' (works as before) parse(a,'data.info') // Returns {name: "mina"} (works as before) parse(a,'data.interested[1]') // Returns 'makeup' (now works!) parse(a,'data.interested[0]') // Returns 'programming' // Test nested arrays const complexObj = {data: {name: [[{name: 'test'}]]}} parse(complexObj, 'data.name[0][0].name[0]') // Returns 'test'
How It Works
- Path Normalization: The regex
/\[(\d+)\]/gfinds all array index patterns like[1]and replaces them with.1. This turns array indices into dot-separated segments that we can process uniformly with property names. - Segment Splitting: We split the normalized path on dots, then filter out any empty segments (this handles edge cases where the path starts with an array index, like
[0].property). - Traverse the Path: We loop through each segment, stepping into the object or array. If any segment leads to an
undefinedvalue, we setcurrenttofalse(matching your original function's behavior) and break the loop. - Return Logic: Just like your original function, we only return the value if it's truthy. If the path is invalid or the value is falsy (e.g.,
0,'',false), the function returnsundefined.
Optional Tweak
If you want the function to return the actual value even if it's falsy (which is often more useful), you can adjust the return statement to:
// Return the value if the path is valid, otherwise return false return current !== false ? current : false;
This way, parse({a: false}, 'a') would return false instead of undefined, which is more intuitive for cases where the value itself is falsy but the path exists.
内容的提问来源于stack exchange,提问作者Mina Pandey

