gpt4 book ai didi

javascript - 从另一个对象构建对象,该对象将其键与数组中的值进行比较

转载 作者:行者123 更新时间:2023-12-04 00:49:37 25 4
gpt4 key购买 nike

以下对象用作填充应用 UI 中选择框选项的起点:

const months = {
"1": "Jan",
"2": "Feb",
"3": "Mar",
"4": "Apr",
"5": "May",
"6": "Jun",
"7": "Jul",
"8": "Aug",
"9": "Sep",
"10": "Oct",
"11": "Nov",
"12": "Dec"
}

虽然基于另一个数组的内容,但必须限制选择框的选项。这是该数组的示例:

const existingMonths = [
1,
2,
3,
4,
5,
6,
7,
8,
12
];

所以在这个例子中,选择框的最终选项的对象应该是:

const availableMonths = {
"9": "Sep",
"10": "Oct",
"11": "Nov"
}

我很难弄清楚如何构建 availableMonths 对象。这不会提供所需的输出:

const availableMonths = Object.entries(months).filter(k => !existingMonths.includes(k));

最佳答案

您需要从条目数组中取出键,并根据数组的值检查键的数值。最后从条目创建一个新对象。

const
months = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" },
existingMonths = [ 1, 2, 3, 4, 5, 6, 7, 8, 12],
availableMonths = Object.fromEntries(Object
.entries(months)
.filter(([k]) => !existingMonths.includes(+k))
);

console.log(availableMonths);

关于javascript - 从另一个对象构建对象,该对象将其键与数组中的值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67588127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com