删除不拥有或继承的属性

Removing properties which are not owned or inherited

本文关键字:属性 继承 拥有 删除      更新时间:2023-09-26

这是我的代码。

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);