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

如何在JavaScript中按键移除对象?移除指定code的数组元素

嘿,我来帮你搞定这两个JavaScript的问题!


在JavaScript中按键移除对象属性

有两种常用的方式,你可以根据需求选择:

1. 使用delete操作符

这是最直接的方法,会直接修改原对象:

const obj = { name: "Alice", age: 30, sku: "123" };
delete obj.sku; // 移除sku属性
console.log(obj); // { name: "Alice", age: 30 }

注意:delete会改变原对象,如果不想影响原始数据,更推荐下面的方法。

2. ES6解构赋值(创建新对象)

这种方法会返回一个不包含目标属性的新对象,原对象完全保持不变:

const obj = { name: "Alice", age: 30, sku: "123" };
const { sku, ...newObj } = obj; // 解构出sku,剩余属性存入newObj
console.log(newObj); // { name: "Alice", age: 30 }
console.log(obj); // 原对象不受影响:{ name: "Alice", age: 30, sku: "123" }

移除数组中code === "sku"的元素

针对你给出的order.attributes_list数组,最简洁安全的方法是用filter()——它会返回一个新数组,不会修改原数组:

// 过滤掉code等于"sku"的元素
const filteredAttributes = order.attributes_list.filter(item => item.code !== "sku");
console.log(filteredAttributes); 
// 输出:[{ code: "show_more_options", label: "Show More Options", value: "New variant!" }]

如果你一定要修改原数组(不推荐,容易引发数据副作用),可以用findIndex()配合splice():

const targetIndex = order.attributes_list.findIndex(item => item.code === "sku");
if (targetIndex !== -1) { // 先确认找到对应元素
  order.attributes_list.splice(targetIndex, 1);
}
console.log(order.attributes_list); // 原数组已移除sku元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:21:31