清除对象属性的更干净方法

时间:2020-02-27 11:24:46

标签: javascript performance object

我创建了一个函数来删除我告诉他的属性

function trimProperties(data, properties) {
  return data.map(o => {
    Object.keys(o).forEach(k => {
      if (properties.includes(k)) {
        delete o[k];
      } 
    });
    return o;
  });
}

我的用例通常是这样的

let array = [
  {
    a: 'A',
    b: 'B',
    c: 'C'
  },
  {
    a: 'A2',
    b: 'B2',
    c: 'C2'
  }
]
// Remove every property 'b' or 'c' from the objects inside the array
trimProperties(array, ['b','c']);

我的问题很简单,我如何使该功能更快,因为我的数组有时会变得很大,因为它是数据库访问的结果集

2 个答案:

答案 0 :(得分:2)

delete导致索引一直在重新计算,创建新数组会更快

let array = [
  {
    a: 'A',
    b: 'B',
    c: 'C'
  },
  {
    a: 'A2',
    b: 'B2',
    c: 'C2'
  }
]

function trimProperties(data, properties) {
  let i = 0;
  const result = []
  while (i < data.length) {
    var o = {};
    Object.keys(data[i]).forEach(k => {
      if (!properties.includes(k)) {
        o[k] = data[i][k];
      } 
    })
    i++;
    if (Object.keys(o).length) {
      result.push(o);
    }
  }
    
  return result;

}

// Remove every property 'b' or 'c' from the objects inside the array
console.log(trimProperties(array, ['b','c']));

答案 1 :(得分:1)

一个班轮:

array.map(o => Object.fromEntries(Object.entries(o).filter(([k,v]) => !['b','c'].includes(k))))

演示:

const array = [
  {
    a: 'A',
    b: 'B',
    c: 'C'
  },
  {
    a: 'A2',
    b: 'B2',
    c: 'C2'
  }
];
const excluded = ['b','c'];

const filtered = array.map(o => Object.fromEntries(Object.entries(o).filter(([k,v]) => !excluded.includes(k))));

console.log(filtered)