React Native JavaScript中如何从对象删除指定键?以移除white键为例
如何从colors对象中移除white键并保留其余键值对?
给你几个实用的实现思路:
1. 解构赋值(不修改原对象)
这是最简洁的写法,直接创建一个不包含white键的新对象,原对象不受影响:
const colors = { "white":"#FFFFFF", "black":"#000000", "red":"FF0000" }; // 解构出white,剩余的键值对存入新对象 const { white, ...restColors } = colors; console.log(restColors); // 输出: { black: "#000000", red: "FF0000" }
2. delete操作符(直接修改原对象)
如果不需要保留原对象,可以直接用delete删除指定键:
const colors = { "white":"#FFFFFF", "black":"#000000", "red":"FF0000" }; // 先判断键是否存在,避免不必要的报错 if (colors.hasOwnProperty('white')) { delete colors.white; } console.log(colors); // 输出: { black: "#000000", red: "FF0000" }
3. 过滤键值对数组(灵活扩展)
如果之后需要添加更多过滤条件,这种方式更灵活:
const colors = { "white":"#FFFFFF", "black":"#000000", "red":"FF0000" }; // 把对象转成键值对数组,过滤掉white项,再转回对象 const restColors = Object.fromEntries( Object.entries(colors).filter(([key]) => key !== 'white') ); console.log(restColors); // 输出: { black: "#000000", red: "FF0000" }
内容的提问来源于stack exchange,提问作者Bhaveen Parghi
相关产品推荐
相关产品推荐

