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

如何使用map和filter将对象数组a转换为目标结构数组c?

Transform Array Using map and filter

Great question! Let's break down how to turn your array a and object b into the target array c using these two array methods.

Core Transformation with map

The main work here is done by map — it lets us loop through every object in a and return a new object that includes the original properties plus the time value from b. We'll use the spread operator (...) to copy all existing properties of each item, then add the time field using the item's a value as the key to look up in b.

const a = [ { a: "hi", b: 0 }, { a: "bye", b: 1 }, { a: "seeyou", b: 2 } ];
const b = { hi: "22:00", bye: "20:00", seeyou: "12:00" };

// This gives you exactly the target array c
const c = a.map(item => ({
  ...item,
  time: b[item.a]
}));

console.log(c);
// Output:
// [
//   { a: "hi", b: 0, time: "22:00" },
//   { a: "bye", b: 1, time: "20:00" },
//   { a: "seeyou", b: 2, time: "12:00" }
// ]

Adding filter for Cleanup (Optional)

If there's a possibility that some objects in a have an a value that doesn't exist as a key in b, we can use filter first to exclude those entries. This prevents us from getting time: undefined in our final array.

// Filter out items with no matching key in b, then map
const cClean = a
  .filter(item => b.hasOwnProperty(item.a))
  .map(item => ({
    ...item,
    time: b[item.a]
  }));

Quick Explanation of the Filter Step:

  • filter checks if the current item's a property is a direct key of b using hasOwnProperty (this avoids checking inherited properties, which is safer than just using item.a in b).
  • Only items that pass this check move on to the map step, where we add the time property as before.

That's all you need! map handles the transformation, and filter adds an extra layer of robustness if you need it.

内容的提问来源于stack exchange,提问作者kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:12:39