javascript - 当对象键javascript中的数组字符串匹配时删除对象
问题描述
我正在使用其他代码,试图不破坏应用程序中的其他功能,但基本上我需要在条件匹配时删除对象。
我之前问的问题会删除对象,但不会在不同的代码库中,所以希望有人能给我一些想法。
谢谢您的帮助!
const data = {
'123': {
'name': 'Part 1',
'size': '20',
'qty' : '50'
},
'5678' : {
'name': 'Part 2',
'size': '15',
'qty' : '60'
},
'9810' : {
'name': 'Part 2',
'size': '15',
'qty' : '120'
},
}
// my code I tried work with:
const getValue = Object.keys(data).reduce((acc,id)=> {
const condition = ['9810','5678'];
if(acc[key]){
// remove the object if the key match
return !acc.includes(key[id])
} else {
// if not match just return the original object
return acc
}
},{})
解决方案
如果您想创建一个具有已删除属性的新对象(这可能是一个好主意),您应该将键处的值分配给累加器,您可以Object.entries
在reduce
回调中使用同时获取键和值。您还可以使用 Set 而不是数组来降低计算复杂度(Set.has
is O(1)
,而Array.includes
is O(n)
):
const data = {
'123': {
'name': 'Part 1',
'size': '20',
'qty': '50'
},
'5678': {
'name': 'Part 2',
'size': '15',
'qty': '60'
},
'9810': {
'name': 'Part 2',
'size': '15',
'qty': '120'
},
}
const condition = new Set(['9810', '5678']);
const filteredData = Object.entries(data).reduce((acc, [key, val]) => {
if (!condition.has(key)) {
acc[key] = val;
}
return acc;
}, {});
console.log(filteredData);
如果您想从现有 对象中实际删除子data
对象(改变data
您已经拥有的),然后迭代forEach
并使用delete
来删除该属性:
const data = {
'123': {
'name': 'Part 1',
'size': '20',
'qty': '50'
},
'5678': {
'name': 'Part 2',
'size': '15',
'qty': '60'
},
'9810': {
'name': 'Part 2',
'size': '15',
'qty': '120'
},
}
const condition = new Set(['9810', '5678']);
Object.keys(data).forEach((key) => {
if (condition.has(key)) {
delete data[key];
}
});
console.log(data);
推荐阅读
- php - PHP 自定义错误处理程序类记录/显示重复错误
- javascript - Optimizing Firebase cloud functions structure in node.js
- java - Java - 如何读取同一目录中的所有文件
- c++ - 用于计算的“|”或“&”与内部 IF 语句之间的区别
- sitefinity - sitefinity ControllerToolboxItem 与 MVC 控制器
- discord.py - Discord.py 错误处理不输出消息?
- c - 如何将纪元 unix 时间转换为 TOD 时钟(STCK)?
- sql - 从文本字段中提取数据
- ios - 当我单击 TabBar 项目时,整个 TabBar 消失....,Swift,Xcode
- javascript - 如何在 Discord.js 中设置 cron 作业