过滤对象属性匹配接口

时间:2016-06-13 13:05:25

标签: angular typescript

我有一些实现某些接口的对象,但它们也有额外的属性。 当我来序列化它们(保存在文件中)时,我想删除所有额外的属性,并且只保留与接口匹配的属性。

有没有办法去清洁"关于给定接口的对象。 我正在尝试

Object.getOwnPropertyNames(myObject)

获取对象属性的完整列表,并与接口属性的完整列表进行比较,但我找不到获取接口属性列表的方法

编辑:我在这里找到了一个方法:How can I create an object based on an interface file definition in TypeScript?

var object = <IMyInterface>{};

但是我看到当我使用Object.getOwnPropertyNames(myObject)时,这仅适用于已定义的属性,如果未定义属性,则它不在结果中。有没有一种方法可以获得所有可用的属性,而不仅仅是已定义的属性?

3 个答案:

答案 0 :(得分:1)

查看此代码:

interface MyInterface1 {
    field1: string;
    field2: string;
}

interface MyInterface2 {
    field3: string;
    field4: string;
}

let o1 = {
    field1: "field1",
    field2: "field2",
    fieldN: "fieldN"
} as MyInterface1;

let o2 = {
    field3: "field3",
    field4: "field4",
    fieldN: "fieldN"
} as MyInterface2;

汇编成:

var o1 = {
    field1: "field1",
    field2: "field2",
    fieldN: "fieldN"
};
var o2 = {
    field3: "field3",
    field4: "field4",
    fieldN: "fieldN"
};

code in playground

所以你可以看到在编译的(js)代码中接口不存在,所以你无法知道(在运行时)需要保留的属性。

你能做的是:

let myInterface1Keys = ["field1", "field2"];
interface MyInterface1 {
    field1: string;
    field2: string;
}

let o1 = {
    field1: "field1",
    field2: "field2",
    fieldN: "fieldN"
} as MyInterface1;

let persistableO1 = {} as MyInterface1;
Object.keys(o1).forEach(key => {
    if (myInterface1Keys.indexOf(key) >= 0) {
        persistableO1[key] = o1[key];
    }
});

code in playground

答案 1 :(得分:0)

我真的很喜欢@Nitzan 的回答,但我遇到的一个问题是,当我更新类型时,硬编码到字符串数组中的键不会更新,从而导致错误,否则会被打字稿捕获。所以我建议也输入键字符串数组,这样打字稿也会提示你更新它,如果你以后改变你的类型:


interface MyInterface1 {
    field1: string;
    field2: string;
}

let o1 = {
    field1: "field1",
    field2: "field2",
    fieldN: "fieldN"
} as MyInterface1;

let myInterface1Keys: Array<keyof MyInterface1> = ["field1", "field2"]; //<--------

let persistableO1 = {} as MyInterface1;
Object.keys(o1).forEach(key => {
    if (myInterface1Keys.indexOf(key) >= 0) {
        persistableO1[key] = o1[key];
    }
});

答案 2 :(得分:-5)

你可以这样做:

&#13;
&#13;
var app = angular.module("myapp", []);
app.controller("AppCtrl", function($scope){
  $scope.person = {
    name : "John",
    surname : "Doe",
    age : 50,
    gender : "male"
	};
});

app.filter("myfilter", function(){
  return function (input, excludeItem) {
    delete input[excludeItem];
    return input;
  }
});
&#13;
<html>
  <head>
    <title>Solutions-1</title>
  </head>
  <body ng-app="myapp">
    <div ng-controller="AppCtrl">
      <div ng-repeat="(key, value) in person | myfilter:'gender'">{{key}} : {{value}}</div>
    </div>
    <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  </body>
</html>
&#13;
&#13;
&#13;

演示: http://codepen.io/Asit124/pen/ZOWJeM