当我想在包含一组字符的json对象中排除某些属性时,我该怎么做?
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:""}
所以现在我要删除包含字符串foo
var result = _.isEqual(
_.omit(obj1, ['\*foo\*']),
_.omit(obj2, ['\*foo\*'])
);
像这样......
我有办法做到这一点吗?
答案 0 :(得分:3)
在香草JS中,
可能不是最好的方法。但你可以这样做
console.log(/"(\/ab\/)"/.test('"/ad/"')); // false
console.log(/"(\/[^\/]*)"/.test('"/ad/"')) // false
console.log(/"(\/ab\/)|(\/[^\/]*)"/.test('"/ad/"')); //true
等
foo
答案 1 :(得分:1)
您可以尝试跟随(它操纵同一个对象)
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);

如果您希望保留对象
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);

答案 2 :(得分:1)
如你所说,你需要使用正则表达式的解决方案,所以你去:
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/);
答案 3 :(得分:1)
您可以将省略的函数传递给第二个参数:
const result = _.omit(obj1, (value, key) => key.includes('foo'))