You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写keyAccessor函数:匹配数组元素与对应对象属性值

How to Implement the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:48:22