You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何复制JavaScript对象并移除指定key的数组元素?

解决方案

你可以结合对象解构和数组的filter()方法来实现,既完成对象的浅克隆,又过滤掉目标项:

const inputsCustomer = {
  title: "customer information",
  inputs: [
    { key: "customerAccount" },
    { key: "customerCity" }
  ]
};

// 克隆对象并过滤指定项
const newInputsCustomer = {
  ...inputsCustomer,
  inputs: inputsCustomer.inputs.filter(item => item.key !== "customerAccount")
};

console.log(newInputsCustomer);

说明:

  • ...inputsCustomer 用对象解构语法复制原对象的所有属性(这里就是title)。
  • 重写inputs属性时,通过filter()方法筛选出key不等于customerAccount的数组项,直接移除目标元素。

如果原对象存在嵌套属性需要深克隆,可以先深克隆原对象再做过滤:

// 深克隆版本
const clonedObj = JSON.parse(JSON.stringify(inputsCustomer));
clonedObj.inputs = clonedObj.inputs.filter(item => item.key !== "customerAccount");

内容的提问来源于stack exchange,提问作者Nextor85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:07:01