Quasar中如何移除对象内指定键对应的条目?
解决对象属性删除报错:splice is not a function
你在Quasar中拥有如下结构的对象:
{ 1: {id: 1, title: 'Supreme Court dubs Manipur', news: 'PTI, New Delhi, JUL 20 2023, 11:23 ISTUPDATED: JUL…isturbing-asks-centre-to-take-action-1238849.html', created_by: 10000001, updated_by: null}, 2: {id: 2, title: 'test for reverse', news: 'reverse test In the above program, the user is pro…d to enter a string. That string is passed to the', created_by: 10000001, updated_by: 10000001}, 12: {id: 12, title: 'cc', news: 'cc', created_by: 10000001, updated_by: null}, 13: {id: 13, title: 'aa', news: 'aa', created_by: 10000001, updated_by: null}, 14: {id: 14, title: 'jj', news: 'jj', created_by: 10000001, updated_by: null}, 15: {id: 15, title: 'mm', news: 'h', created_by: 10000001, updated_by: null} }
你尝试用以下代码移除键为12的条目:
let id = 12 master.news.splice(id, 1)
但触发报错:Uncaught TypeError: master.news.splice is not a function
问题原因
splice是数组的专属方法,而master.news是键值对格式的对象,数据类型不匹配,因此无法调用该方法。
解决方案
删除对象的指定键值对,可使用以下两种方法:
- 直接修改原对象(操作简单)
用JavaScript原生delete操作符直接移除目标键:
let id = 12 delete master.news[id]
- 生成新对象保留原数据
若需保留原对象,可通过解构赋值创建排除目标键的新对象:
let id = 12 const { [id]: _, ...newNews } = master.news master.news = newNews
内容的提问来源于stack exchange,提问作者Sona Rijesh
相关产品推荐
相关产品推荐

