【问题标题】:Delete the object in place from an array: JS [duplicate]从数组中删除对象:JS [重复]
【发布时间】:2022-01-07 08:09:15
【问题描述】:

我有一个具有以下结构的对象数组:

const timeOptions = [
  { key: "all", value: "all", text: "All" },
  { key: "month", value: "month", text: "Month" },
  { key: "year", value: "year", text: "Year" }
];

我正在创建一个新对象,其中 timeOptions 是其中一个字段的值。如何在创建对象本身时使用键“all”in-place 删除对象

const values = {
  timeVal: {
    field: "timestamp",
    label: "Timestamp",
    options: timeOptions
  }
};

我尝试过的代码


const values = {
  timeVal: {
    field: "timestamp",
    label: "Timestamp",
    options: timeOptions.forEach((k) => delete k["key"] === "all")
  }
};

【问题讨论】:

    标签: javascript arrays ecmascript-6


    【解决方案1】:

    使用Array#filter

    options: timeOptions.filter(({ key }) => key !== 'all')
    

    【讨论】:

    • 这是一个明显且经常重复的副本。
    【解决方案2】:

    如果我理解正确,您需要过滤器

    const values = {
     timeVal: {
     field: "timestamp",
     label: "Timestamp",
     options: timeOptions.filter((k) =>  k["key"] !== "all")
    }
    

    };

    这将复制所有内容,除了键为“all”的那个

    【讨论】:

    • 这是一个明显且经常重复的副本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 2021-07-01
    相关资源
    最近更新 更多