删除不拥有或继承的属性
Removing properties which are not owned or inherited
这是我的代码。
function Material() {
this.id = null;
}
function Box() {
// Inherit Material props
Material.call(this)
// Define own props
this.width = null;
this.height = null;
this.weight = null;
}
var box = new Box();
// Setting values to Box props
box.id = 12;
box.width = 250;
box.height = 350;
box.weight = '10kg';
// Not its property
box.color = 'red';
// TODO: Passing box variable via function which will return new object of Box without color property
console.log(box);
// {
// 'id': 12,
// 'width': 250,
// 'height': 350,
// 'weight': '10kg',
// }
所以基本上在某些时候我想摆脱在盒子对象上设置的颜色属性(这不是 Box 类的属性)。
我不想单独删除此类属性,因为可能有很多。我无法找出要删除的属性。但我只知道要保留哪些属性(它自己的和继承的)。
我在这里使用洛达什。我试着和_.defaults
一起_.forIn
,但没有帮助。
谢谢
试试这些:
var diff = _.difference(_.keys(box), _.keys(new Box()));
var clear = _.omit(box, diff);
console.log(clear);
clear
- 是具有初始属性集合box
对象的副本
您可以创建一个虚拟Box
对象,循环访问对象的属性并检查虚拟对象是否包含它:
function Material() {
this.id = null;
}
function Box() {
// Inherit Material props
Material.call(this)
// Define own props
this.width = null;
this.height = null;
this.weight = null;
}
function removeAdditionalProperties(obj) {
var dummy = new Box();
for (var key in obj) {
if (!dummy.hasOwnProperty(key)) {
delete obj[key]; // Or whatever you want to do with that prop
}
}
}
var box = new Box();
// Setting values to Box props
box.id = 12;
box.width = 250;
box.height = 350;
box.weight = '10kg';
// Not its property
box.color = 'red';
removeAdditionalProperties(box);
console.log(box);
相关文章:
- 当使用控制器作为语法时,如何从父指令继承属性
- Javascript嵌套函数属性继承
- 继承的属性检查
- 如何防止在javascript中执行继承属性的getter-setter方法
- JavaScript 属性继承
- 无法使用 Snap.SVG将“填充”属性设置为“继承”
- 为什么函数对象的实例没有继承函数原型属性
- AngularJS观察指令属性表达式,动态继承作用域
- Javascript 类继承.子类更改主类的属性
- 继承的Javascript对象将丢失属性值
- 原型继承和原型属性
- (Javascript)覆盖对象内置或继承的属性
- Javascript中的“私有”属性继承
- Angular 1.4.8/JS:创建构造函数并将属性继承到第三个对象中
- JavaScript将对象作为属性继承
- JavaScript中的原型和属性继承
- 我如何正确地使一个构造器的prototype属性继承它原来的prototype属性?
- JS对象的属性继承
- 在 ES2015 中实现简单属性继承
- Javascript中的属性继承