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

时间:2021-05-18 14:17:50

标签: javascript

以下对象用作填充应用程序 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));

3 个答案:

答案 0 :(得分:4)

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

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);

答案 1 :(得分:1)

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 = Object.fromEntries(
   Object.entries(months).filter(([k, v]) => !existingMonths.includes(+k))
)

console.log(availableMonths)

答案 2 :(得分:1)

第一步:浅拷贝月对象
第 2 步:循环访问 existingMonths
第 3 步:通过与 existingMonths 比较来删除浅复制的属性 元素

let
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.assign(availableMonths,months);

existingMonths.forEach((monthNumber) =>{delete availableMonths[monthNumber]})
   

console.log(availableMonths);