我知道我可以使用 rest 运算符从对象中删除一个键,例如
const myObject = {
a: 1,
b: 2,
c: 3
};
const { a, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }
但是如果直到运行时才知道 key 名称怎么办(例如随机生成的 ID)const myobject = {
cke503: { Fake: '1' },
cke502: { Fake: '2' },
cke501: { Fake: '3' },
};
我直到运行时才知道 ID,所以我使用 const id = Object.Keys(myobject)[2] 来获取 'cke501' const id = Object.Keys(myobject)[2] // -> 'cke501'
const { [id], ...rest } = myobject; // -> This doesn't work
最佳答案
您需要指定一个变量名来将值放入其中,但变量名不能是动态的,因此您必须使用与计算属性非常相似的语法 const { [prop]: propVal, ...noA } = myObject;
:
const myObject = {
a: 1,
b: 2,
c: 3
};
const prop = 'a'; // Substitute this with the runtime property calculation
const { [prop]: propVal, ...noA } = myObject;
console.log(noA); // => { b: 2, c: 3 }
console.log(propVal);
关于javascript - 我怎样才能从对象中删除一个键,不可变,除非在您执行删除之前不知道键名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63531979/