简体   繁体   中英

omit multiple keys by wildcard or regex during compare

When i want to exclude some properties in a json object that contain a set of characters, how can i do this?

var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}
var obj2 = {name: "Maria", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}

so now i want to remove all properties that contains the string foo

var result = _.isEqual(
  _.omit(obj1, ['\*foo\*']),
  _.omit(obj2, ['\*foo\*'])
);

something like this...

Is there a way i can do this?

In vanilla JS,

May be not the best approach. But you can do this in the way

  1. Filter the keys having foo etc
  2. Get key value pairs from the original array based on the filtered key
  3. Create a final object

 var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""} var obj2 = {name: "Maria", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}; var o = Object.keys(obj1).filter(o=> !o.includes('foo')), i = o.map(i=> ({[i] : obj1[i]})), obj = Object.assign({}, ...i); console.log(obj) 

You can try following (it manipulates the same object)

 function removeProps (obj, prop) { Object.keys(obj).forEach((key) => { if(key.indexOf(prop) !== -1) delete obj[key]; }); } var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}; removeProps(obj1, "foo"); console.log(obj1); 

In case you wish to preserve the object

 function removeProps (obj, prop) { obj = JSON.parse(JSON.stringify(obj)); Object.keys(obj).forEach((key) => { if(key.indexOf(prop) !== -1) delete obj[key]; }); return obj; } var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}; var obj1Updated = removeProps(obj1, "foo"); console.log(obj1); console.log(obj1Updated); 

As you mentioned that you need the solution using regex so here you go:

var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""}
var obj2 = {name: "Maria", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""};

Object.prototype.filterRegex = function(regex) {
    // check if regex is passed
    let filtered = Object.keys(this).filter((key) => !regex.test(key));
    return filtered.reduce((obj, key) => {
        obj[key] = this[key];
        return obj;
    }, {});
};

obj1.filterRegex(/foo/);
obj2.filterRegex(/foo/);

您可以忽略一个将键作为第二个参数的函数:

const result = _.omit(obj1, (value, key) => key.includes('foo'))

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