将数组中的多个值匹配到对象数组
Posted
技术标签:
【中文标题】将数组中的多个值匹配到对象数组【英文标题】:Matching multiple values from array to object array 【发布时间】:2022-01-17 04:26:49 【问题描述】:我正在尝试创建一个预订应用程序并标记出不可用的插槽。不可用的插槽在数组中,例如:
const unavailable = [ "11:00am a 12:00pm", "17:00pm a 18:00pm"]
总槽数为
let slots = [
slot: "9:00am a 10:00am",
isReserved: false,
,
slot: "10:00am a 11:00am",
isReserved: false,
,
slot: "11:00am a 12:00pm", isReserved: false ,
slot: "15:00pm a 16:00pm",
isReserved: false,
,
slot: "17:00pm a 18:00pm",
isReserved: false,
,
slot: "18:00pm a 19:00pm",
isReserved: false,
,
slot: "19:00pm a 20:00pm", isReserved: false ,
];
我的目标是使用不可用的数组和其中的每个值,并找到如何将该字段更改为
isReserved: true
我试过这样过滤
const matches = slots.filter((same) => same.slot === unavailable);
但不起作用。做了什么样的工作是
const matches = slots.filter((same) => same.slot === unavailable[0]);
但那只匹配第一个值,我仍然不知道如何更改 isReserved 字段。
【问题讨论】:
你想要一个新数组还是改变旧数组? 我想变异,但要么或应该为我需要的东西工作 【参考方案1】:如果找到插槽,您可以迭代和更新。
const
unavailable = ["11:00am a 12:00pm", "17:00pm a 18:00pm"],
slots = [ slot: "9:00am a 10:00am", isReserved: false , slot: "10:00am a 11:00am", isReserved: false , slot: "11:00am a 12:00pm", isReserved: false , slot: "15:00pm a 16:00pm", isReserved: false , slot: "17:00pm a 18:00pm", isReserved: false , slot: "18:00pm a 19:00pm", isReserved: false , slot: "19:00pm a 20:00pm", isReserved: false ];
slots.forEach(o =>
if (unavailable.some(slot => slot === o.slot)) o.isReserved = true;
);
console.log(slots);
.as-console-wrapper max-height: 100% !important; top: 0;
如果您不想改变原始数组,可以使用新属性映射对象。
const
unavailable = ["11:00am a 12:00pm", "17:00pm a 18:00pm"],
slots = [ slot: "9:00am a 10:00am", isReserved: false , slot: "10:00am a 11:00am", isReserved: false , slot: "11:00am a 12:00pm", isReserved: false , slot: "15:00pm a 16:00pm", isReserved: false , slot: "17:00pm a 18:00pm", isReserved: false , slot: "18:00pm a 19:00pm", isReserved: false , slot: "19:00pm a 20:00pm", isReserved: false ],
result = slots.map(o => (
...o,
isReserved: o.isReserved || unavailable.some(slot => slot === o.slot)
));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
【讨论】:
您提供的第二个选项效果很好!为我节省了很多时间,非常感谢!【参考方案2】:你可以使用地图操作符,可以做到这一点。
const unavailable = [ "11:00am a 12:00pm", "17:00pm a 18:00pm"]
let slots = [
slot: "9:00am a 10:00am",
isReserved: false,
,
slot: "10:00am a 11:00am",
isReserved: false,
,
slot: "11:00am a 12:00pm", isReserved: false ,
slot: "15:00pm a 16:00pm",
isReserved: false,
,
slot: "17:00pm a 18:00pm",
isReserved: false,
,
slot: "18:00pm a 19:00pm",
isReserved: false,
,
slot: "19:00pm a 20:00pm", isReserved: false ,
];
const slots = slots.map(slotobj=>
if(unavailable.includes(slotobj.slot))
slotobj.isReserved =true
return slotobj;
)
【讨论】:
以上是关于将数组中的多个值匹配到对象数组的主要内容,如果未能解决你的问题,请参考以下文章