我正在使用其他人的代码,试图不破坏应用程序的其他功能,但基本上我需要在条件匹配时删除对象。
我之前提出的问题将删除对象,但不会在其他代码库中删除,因此希望有人可以给我一些想法。
感谢您的帮助!
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
}
},{})
答案 0 :(得分:0)
如果要使用删除的属性创建一个新对象(这可能是个好主意),则应将键上的值分配给累加器,并且可以使用Object.entries
来获取两个键和reduce
回调中的值。您还可以使用Set而不是数组来降低计算复杂度(Set.has
是O(1)
,而Array.includes
是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
进行突变),请使用{{1}进行迭代},然后使用forEach
删除属性:
delete
答案 1 :(得分:0)
要删除子对象中包含在键数组中的所有对象,请使用default
和Vue.component('nav-section', require('./components/Navigation.vue').default);
。
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 = ["5678", "9810"];
condition.forEach(key => delete data[key]);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: auto; }