Greggz
Greggz

Reputation: 1809

Cleaner way to filter properties from object

I created a function to remove the properties I tell him to

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

My use case is usually like this

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']);

My question is simple, how can I make this function faster, because my array sometimes can get pretty big since it's the result set from a database access

Upvotes: 0

Views: 43

Answers (2)

cthmsst
cthmsst

Reputation: 374

A one liner:

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

Demo:

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)

Upvotes: 1

qiAlex
qiAlex

Reputation: 4346

delete cause indexes recalculation all the time, creating new array would be faster

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']));

Upvotes: 2

Related Questions