编写keyAccessor函数:匹配数组元素与对应对象属性值
keyAccessor Function Got it, let's break down how to build this function exactly as you described. The goal is to take an array of names (which are all keys in the given object) and return a new array containing the corresponding values from that object.
Simple Implementation Using map()
The cleanest way to do this is with JavaScript's Array.prototype.map() method—it's made for transforming each element in an array, which is exactly what we need here:
function keyAccessor(namesArray, dataObject) { // Iterate over each name in the array, fetch its value from the object return namesArray.map(name => dataObject[name]); }
Example Walkthrough
Let's use sample inputs to see how this works:
- Names Array:
["Luna", "Gavin", "Mia"] - Data Object:
{ Luna: "Designer", Gavin: "Engineer", Mia: "Manager", Zoe: "Writer" }
When we call keyAccessor(["Luna", "Gavin", "Mia"], { Luna: "Designer", Gavin: "Engineer", Mia: "Manager", Zoe: "Writer" }), the function will return:["Designer", "Engineer", "Manager"]
Handling Edge Cases (Optional)
If there's a chance some names in the array don't exist as keys in the object, the basic function will return undefined for those entries. If you want to filter those out, you can chain a filter() method:
function keyAccessor(namesArray, dataObject) { return namesArray .map(name => dataObject[name]) // Remove any undefined values from the result .filter(value => typeof value !== 'undefined'); }
That's it! This function is concise, readable, and does exactly what you need.
内容的提问来源于stack exchange,提问作者Devin Bowen

