Skip to content
Advertisement

How do I filter out a key from an object?

I have following object in JS. How can I select all keys except the first financial_year and put it into a new empty object?

I understand I can do something like obj["mainline_revenue"] to select individual elements but its a long list and I don’t want to type elements keys individually.

var obj = {financial_year: 1, mainline_revenue: 18743, regional_revenue: 2914, other_revenue: 3198, salaries_wages: -6897}

var newObj = {}

New object would look like this:

console.log(newObj)
{mainline_revenue: 18743, regional_revenue: 2914, other_revenue: 3198, salaries_wages: -6897}

Advertisement

Answer

You could just clone the object with Object.assign then use delete to removed the undesired property:

var newObj = Object.assign({}, obj);
delete newObj.financial_year;

Of course there are other more functional ways to achieve this, maybe by filtering the keys, then reducing to an object:

var newObj = Object.keys(obj).filter(key => 
  key !== 'financial_year'
).reduce((newObj, currKey) =>
  (newObj[currKey] = obj[currKey], newObj), 
{});

Though this approach would be more suited if you had an array of keys you wanted to filter out, and you could just check if the key was in the array in the filter callback.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement