删除不拥有或继承的属性

时间:2015-02-03 12:30:02

标签: javascript lodash

这是我的代码。

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对象上设置的颜色属性(这不是Box类的属性)。

我不想单独删除这些属性,因为可能有很多。我无法找出要删除的属性。但我只知道要保留哪些属性(它自己和继承)。

我在这里使用lodash。我和_.forIn一起尝试_.defaults但没有帮助。

由于

2 个答案:

答案 0 :(得分:3)

尝试these

var diff = _.difference(_.keys(box), _.keys(new Box()));
var clear = _.omit(box, diff);
console.log(clear);

clear - 是具有初始属性集

box对象的副本

答案 1 :(得分:1)

您可以创建一个虚拟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);
相关问题