当对象关键字javascript中的数组字符串匹配时,删除对象

时间:2019-07-28 01:33:21

标签: javascript arrays object reduce

我正在使用其他人的代码,试图不破坏应用程序的其他功能,但基本上我需要在条件匹配时删除对象。

我之前提出的问题将删除对象,但不会在其他代码库中删除,因此希望有人可以给我一些想法。

感谢您的帮助!

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
   }
},{})

2 个答案:

答案 0 :(得分:0)

如果要使用删除的属性创建一个新对象(这可能是个好主意),则应将键上的值分配给累加器,并且可以使用Object.entries来获取两个键和reduce回调中的值。您还可以使用Set而不是数组来降低计算复杂度(Set.hasO(1),而Array.includesO(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)

要删除子对象中包含在键数组中的所有对象,请使用defaultVue.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; }