过滤掉不属于某个类的属性

时间:2017-10-25 09:09:59

标签: javascript typescript ecmascript-6

如何过滤掉课程Car上不存在的属性?

class Car {
    wheels: number;
    model: string;
}


const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'};

const goodCar = filterUnwantedProps(obj); // goodCar only has fields wheels and model

如何保留obj,只保留课程Car上的字段?

3 个答案:

答案 0 :(得分:2)

您可以对reduce()类的新实例的键使用Car,并仅采用对象上存在的属性。



class Car {
  constructor() {
    this.wheels = Number();
    this.model = String();
  }
}

const obj = {
  wheels: 4,
  model: 'foo',
  unwanted1: 'bar',
  unwantedn: 'kuk'
};


var goodObj = Object.keys(new Car)
  .reduce(function(r, e) {
    if (e in obj) r[e] = obj[e];
    return r;
  }, {});

console.log(goodObj)




答案 1 :(得分:1)

只需使用contructor:

class Car {
  constructor(wheels, model) {
    this.wheels = wheels;
    this.model = model;
  }
}

const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'};

const goodCar = new Car(obj.wheels, obj.model);

console.log(goodCar);

OR:

class Car {
  constructor(obj) {
    this.wheels = obj.wheels;
    this.model = obj.model;
  }
}

const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'};

const goodCar = new Car(obj);

console.log(goodCar);

答案 2 :(得分:1)

另一种选择是使用object destructuring并从函数中返回对象:

const filterUnwantedProps = function({
  wheels: wheels,
  model: model
}) {
  return {
    wheels: wheels,
    model: model
  }
};

示例代码:



class Car {
  wheels: number;
  model: string;
};

const obj = {
  wheels: 4,
  model: 'foo',
  unwanted1: 'bar',
  unwantedn: 'kuk'
};

const filterUnwantedProps = function({
  wheels: wheels,
  model: model
}) {
  return {
    wheels: wheels,
    model: model
  }
};
const goodCar = filterUnwantedProps(obj);
console.log(goodCar);