简体   繁体   中英

Removing keys from object via regex

I have this following object:

  {
      id: 'txn_000000000'
      customer: 'cus_00000000000000',
      customer_address: null,
      customer_email: 'foo@bar.com',
      customer_name: 'Foo Bar',
      customer_phone: null,
      customer_shipping: null,
      customer_tax_exempt: 'none',
      customer_tax_ids: [],
  }

I want to remove all keys from the object which start with customer_ for GDPR reasons, do you know if this is possible in JS? (Specifically NodeJS)

This is independant of NodeJs

Given your object o , you can just filter the keys and reconstitute your object:

 const o = { id: 'txn_000000000', customer: 'cus_00000000000000', customer_address: null, customer_email: 'foo@bar.com', customer_name: 'Foo Bar', customer_phone: null, customer_shipping: null, customer_tax_exempt: 'none', customer_tax_ids: [], } let grpdCompliant = Object.keys(o).filter(k => { return !k.startsWith('customer_') }).reduce((acc, k)=>{ acc[k] = o[k] return acc },{}) console.log(grpdCompliant)


edit: even better proposed by Andreas:

Object.fromEntries(Object.entries(o).filter(e => !e[0].startsWith("customer_")))
for (const key of Object.keys(obj)) {
  if (/^customer_/.test(key)) {
    delete obj[key]
  }
}

where obj is your object.

Note: using that technique your object will be mutated.

if you fancy using lodash, you could do it in one line

  const _ = require("lodash");
_.pick(input, _.keys(input).filter(i => !i.startsWith("customer")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM