Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to copy JS object and filter out certain properties

If I have a JS object, and I'd like to create a new object which copies over all properties except for a blacklist of properties that need to be filtered out, what's the simplest way to do it?

So I would do something like

originalObject.copyAndFilter('a', 'b')

Which would take the original object, copy it, and make sure properties a and b aren't in the new object.

I'm using ES2015/2016 through Babel so if it provides an even simpler way that would work too.

like image 914
user779159 Avatar asked Oct 19 '22 00:10

user779159


2 Answers

You could use Set and delete the unwanted properties.

var object = { a: 1, b: 2, c: 3, d: 4 },
    filteredObject = {},
    p = new Set(Object.keys(object));
    blacklist = ['a', 'b'];

blacklist.forEach(a => p.delete(a));

[...p].forEach(k => filteredObject[k] = object[k]);
console.log(filteredObject);
like image 76
Nina Scholz Avatar answered Oct 27 '22 10:10

Nina Scholz


Well, there's no simple native way to do it, I would convert the keys to an array, filter it, then create a new object:

const obj = {a: 'foo', b: 'bar', c: 'baz'};
const blacklist = ['a', 'b'];

const keys = Object.keys(obj);
const filteredKeys = keys.filter(key => !blacklist.includes(key));

const filteredObj = filteredKeys.reduce((result, key) => {
  result[key] = obj[key];
  return result;
}, {});

console.log(filteredObj);
like image 30
Madara's Ghost Avatar answered Oct 27 '22 11:10

Madara's Ghost