如何使用map和filter将对象数组a转换为目标结构数组c?
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:
filterchecks if the current item'saproperty is a direct key ofbusinghasOwnProperty(this avoids checking inherited properties, which is safer than just usingitem.a in b).- Only items that pass this check move on to the
mapstep, where we add thetimeproperty 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

