Filter object properties

I have some objects that implement some interfaces, but they also have additional properties. When I come to serialize them (for saving to a file), I would like to remove all additional properties and save only the properties corresponding to the interface.

Is there a way to "clear" an object from this interface. I tried with

Object.getOwnPropertyNames(myObject)

To get a complete list of properties of an object and compare with a complete list of properties of an interface, but I cannot find a way to get a list of properties of an interface

Edit: I found a way here: How to create an object based on the definition of an interface file in TypeScript?

WITH

var object = <IMyInterface>{};

But I saw that when I use Object.getOwnPropertyNames (myObject), it only works for certain properties, if the property is not defined, it is not the result. Is there a way to get all the useful properties, not just specific ones?

+4
source share
2 answers

Check this code:

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;

It compiles to:

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

( code on the playground )

So, you can see that the interfaces do not exist in the compiled (js) code, so you have no way to find out (at runtime) which properties you need to save.

What can you do:

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 on the playground )

+1
source

You can do the following:

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;
  }
});
<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>
Run codeHide result

Demo: http://codepen.io/Asit124/pen/ZOWJeM

-3
source

All Articles