首页 > 解决方案 > 当对象键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
   }
},{})

标签: javascriptarraysobjectreduce

解决方案


如果您想创建一个具有已删除属性的新对象(这可能是一个好主意),您应该将键处的值分配给累加器,您可以Object.entriesreduce回调中使用同时获取键和值。您还可以使用 Set 而不是数组来降低计算复杂度(Set.hasis O(1),而Array.includesis 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);


推荐阅读