Convert javascript class instance to plain object preserving methods - javascript

I want to convert an instance class to plain object, without losing methods and/or inherited properties. So for example:
class Human {
height: number;
weight: number;
constructor() {
this.height = 180;
this.weight = 180;
}
getWeight() { return this.weight; }
// I want this function to convert the child instance
// accordingly
toJSON() {
// ???
return {};
}
}
class Person extends Human {
public name: string;
constructor() {
super();
this.name = 'Doe';
}
public getName() {
return this.name;
}
}
class PersonWorker extends Person {
constructor() {
super();
}
public report() {
console.log('I am Working');
}
public test() {
console.log('something');
}
}
let p = new PersonWorker;
let jsoned = p.toJSON();
jsoned should look like this:
{
// from Human class
height: 180,
weight: 180,
// when called should return this object's value of weight property
getWeight: function() {return this.weight},
// from Person class
name: 'Doe'
getName(): function() {return this.name},
// and from PersonWorker class
report: function() { console.log('I am Working'); },
test: function() { console.log('something'); }
}
Is this possible to achieve, and if so, how?
In case you're wondering, I need this because I am using a framework that, unfortunately, accepts as input only an object, whereas I am trying to use TypeScript and class inheritance.
Also, I am doing the above conversion once so performance isn't an issue to consider.
The solutions consisting of iterating through object properties will not work if the compiler's target option is set to es6. On es5, the existing implementations by iterating through object properties (using Object.keys(instance)) will work.
So far, I have this implementation:
toJSON(proto?: any) {
// ???
let jsoned: any = {};
let toConvert = <any>proto || this;
Object.getOwnPropertyNames(toConvert).forEach((prop) => {
const val = toConvert[prop];
// don't include those
if (prop === 'toJSON' || prop === 'constructor') {
return;
}
if (typeof val === 'function') {
jsoned[prop] = val.bind(this);
return;
}
jsoned[prop] = val;
const proto = Object.getPrototypeOf(toConvert);
if (proto !== null) {
Object.keys(this.toJSON(proto)).forEach(key => {
if (!!jsoned[key] || key === 'constructor' || key === 'toJSON') return;
if (typeof proto[key] === 'function') {
jsoned[key] = proto[key].bind(this);
return;
}
jsoned[key] = proto[key];
});
}
});
return jsoned;
}
But this is still not working. The resulted object includes only all the properties from all classes but only methods from PersonWorker.
What am I missing here?

Lots of answers already, but this is the simplest yet by using the spread syntax and de-structuring the object:
const {...object} = classInstance

This is what's working for me
const classToObject = theClass => {
const originalClass = theClass || {}
const keys = Object.getOwnPropertyNames(Object.getPrototypeOf(originalClass))
return keys.reduce((classAsObj, key) => {
classAsObj[key] = originalClass[key]
return classAsObj
}, {})
}

Ok, so the implementation in my OP was wrong, and the mistake was simply stupid.
The correct implementation when using es6 is:
toJSON(proto) {
let jsoned = {};
let toConvert = proto || this;
Object.getOwnPropertyNames(toConvert).forEach((prop) => {
const val = toConvert[prop];
// don't include those
if (prop === 'toJSON' || prop === 'constructor') {
return;
}
if (typeof val === 'function') {
jsoned[prop] = val.bind(jsoned);
return;
}
jsoned[prop] = val;
});
const inherited = Object.getPrototypeOf(toConvert);
if (inherited !== null) {
Object.keys(this.toJSON(inherited)).forEach(key => {
if (!!jsoned[key] || key === 'constructor' || key === 'toJSON')
return;
if (typeof inherited[key] === 'function') {
jsoned[key] = inherited[key].bind(jsoned);
return;
}
jsoned[key] = inherited[key];
});
}
return jsoned;
}

Here is the implementation for the toJSON() method. We are copying over the properties & methods from the current instance to a new object and excluding the unwanted methods i.e. toJSON and constructor.
toJSON() {
var jsonedObject = {};
for (var x in this) {
if (x === "toJSON" || x === "constructor") {
continue;
}
jsonedObject[x] = this[x];
}
return jsonedObject;
}
I have tested the object returned by toJSON() in Chrome and I see the object behaving the same way as you are expecting.

I'm riffing on Alex Cory's solution a lot, but this is what I came up with. It expects to be assigned to a class as a Function with a corresponding bind on this.
const toObject = function() {
const original = this || {};
const keys = Object.keys(this);
return keys.reduce((classAsObj, key) => {
if (typeof original[key] === 'object' && original[key].hasOwnProperty('toObject') )
classAsObj[key] = original[key].toObject();
else if (typeof original[key] === 'object' && original[key].hasOwnProperty('length')) {
classAsObj[key] = [];
for (var i = 0; i < original[key].length; i++) {
if (typeof original[key][i] === 'object' && original[key][i].hasOwnProperty('toObject')) {
classAsObj[key].push(original[key][i].toObject());
} else {
classAsObj[key].push(original[key][i]);
}
}
}
else if (typeof original[key] === 'function') { } //do nothing
else
classAsObj[key] = original[key];
return classAsObj;
}, {})
}
then if you're using TypeScript you can put this interface on any class that should be converted to an object:
export interface ToObject {
toObject: Function;
}
and then in your classes, don't forget to bind this
class TestClass implements ToObject {
toObject = toObject.bind(this);
}

This solution will lose methods, but it is a very simple solution to convert a class instance to an object.
obj = JSON.parse(JSON.stringify(classInstance))

using Lodash
This method isn't recursive.
toPlainObject() {
return _.pickBy(this, item => {
return (
!item ||
_.isString(item) ||
_.isArray(item) ||
_.isNumber(item) ||
_.isPlainObject(item)
);
});
}

Related

Javascript - traverse tree like object and add a key

Suppose I have an object with depth-N like:
food = {
'Non-Animal': {
'Plants' : {
'Vegetables': {
...
}
},
'Minerals' : {
...
}
},
'Animal': {
...
}
}
And I want to add in this object the category 'Fruits', but I have to search the object where 'Plants' are and then add it. So I don't want to do in one statement:
food['Non-Animal']['Plants']['Fruits'] = {};
Since I want to search first where it belongs.
How can I add the fruits category to the object while iterating through it? What I have so far is:
addCategory(food, category, parent);
function addCategory(obj, category, parent_name) {
for (var key in obj) {
if (key == parent_name) {
obj[key][category] = {};
}
var p = obj[key];
if (typeof p === 'object') {
addCategory(p, category, parent);
} else {
}
}
}
How can I fix this routine to do this or is there a better way to do this?
If I'm understanding you correctly, I think you'd want your function to define a variadic parameter that takes individual names of the path you wish to traverse and create if necessary.
Using .reduce() for this makes it pretty easy.
const food = {
'Non-Animal': {
'Plants': {
'Vegetables': {}
},
'Minerals': {}
},
'Animal': {}
}
console.log(addCategory(food, "Non-Animal", "Plants", "Fruits"));
console.log(addCategory(food, "Non-Animal", "Minerals", "Gold"));
function addCategory(obj, ...path) {
return path.reduce((curr, name) => {
if (!curr) return null;
if (!curr[name]) return (curr[name] = {});
return curr[name];
// More terse but perhaps less readable
// return curr ? curr[name] ? curr[name] : (curr[name]={}) : null;
}, obj);
}
console.log(JSON.stringify(food, null, 2));
Looks fine. However you might want to terminate after adding the prop:
function addCategory(obj, category, parent_name) {
for (var key in obj) {
if (key == parent_name){
return obj[key][category] = {};
}
var p = obj[key];
if (typeof p === 'object') {
if(addCategory(p, category, parent)) return true;
}
}
}
I see only one mistake: The recursive call of addCategory cannot find the parent-variable, cause it's called parent_name in your scope.
var food = {
'Non-Animal': {
'Plants' : {
'Vegetables': {
}
},
'Minerals' : {}
},
'Animal': {}
}
function addCategory(obj, category, parent_name) {
for (var key in obj) {
if (key == parent_name){
obj[key][category] = {};
}
var p = obj[key];
if (typeof p === 'object') {
addCategory(p, category, parent_name);
} else {
}
}
}
console.log(food);
addCategory(food, 'Fruits', 'Plants');
console.log(food);
You can use reduce to create function that will take key as string and object as value that you want to assign to some nested object.
var food = {"Non-Animal":{"Plants":{"Vegetables":{}},"Minerals":{}},"Animal":{}}
function add(key, value, object) {
key.split('.').reduce(function(r, e, i, arr) {
if(r[e] && i == arr.length - 1) Object.assign(r[e], value);
return r[e]
}, object)
}
add('Non-Animal.Plants', {'Fruits': {}}, food)
console.log(food)

How do I change the "this" pointer in JavaScript?

I made an object like this:
var MyObj = function(arg)
{
var PublicMethods = {
SomeMethod: function(someArg)
{
if(SomeCheck(arg)
{
PublicMethods.SomeFunc2 = somethingElse;
}
}
};
return PublicMethods;
};
However MyObj doesn't seem to be persistent and between calls, PublicMethods doesnt preserve the new methods added to it, so I tried moving it to global scope, however then it doesn't recognize the 'args' passed from MyObj anymore.
If I make MyObj like this:
var MyObj = (function()
{
//..
}());
Then it becomes a persistent object, but I'm not sure - can I call it like a function again?
jQuery seems to have a persistent object and at the same time it can be called like a function, how do they achieve that?
I want to be able to do this:
MyObj("Something Here").SomeMethod("Something Else");
and thus to be able to create a SomeFunc2 method that I can later call too:
MyObj("Something Here").SomeFunc2("Something Else");
Simply store the result of the initial MyObj call in a local variable:
var obj = MyObj("Something Here");
obj.SomeMethod("Something Else");
obj.SomeFunc2("Something else");
The PublicMethods variable is specific to each call of MyObj, so when you call MyObj for the second time, you get a different instance of PublicMethods. By using a variable to store the result of the first MyObj call, you can use the same instance of PublicMethods for both the SomeMethod and SomeFunc2 functions.
As a side note, you may want to look into constructor functions which would allow you to define functions more simply, instead of returning an object. For example:
function Example() {
this.a = function() {
return "a";
};
this.b = function() {
this.a = function() {
return "b";
}
}
}
var example = new Example();
example.a(); // => "a"
example.b();
example.a(); // => "b"
You can create a jQuery method which extends jQuery or jQuery.fn and can also set this context within the method.
(function($) {
jQuery.addMethod = function addMethod({methodName, method, type}) {
let bool = {
[type]: false
};
let _jQuery_jQueryFn_ = Object.keys(bool).pop();
if (type === "jQuery") {
for (let prop in jQuery) {
if (prop === methodName
|| prop.toUpperCase() === methodName.toUpperCase()) {
bool[type] = true;
break;
}
}
}
if (type === "fn") {
for (let prop in jQuery.fn) {
if (prop === methodName
|| prop.toUpperCase() === methodName.toUpperCase()) {
bool[type] = true;
break;
}
}
}
if (type === "jQuery" && bool[_jQuery_jQueryFn_] === false) {
jQuery[methodName] = method;
}
if (type === "fn" && bool[_jQuery_jQueryFn_] === false) {
jQuery[type][methodName] = method;
}
if (bool[_jQuery_jQueryFn_] === true) {
return Promise.reject(
new ReferenceError(
methodName
+ " previously defined at "
+ _jQuery_jQueryFn_
));
} else {
console.log(methodName + " defined at " + _jQuery_jQueryFn_);
}
return {methodName:methodName, type};
}
})(jQuery);
$(function() {
Promise.resolve($.addMethod({
methodName: "add",
method: function add(a, b, context) {
console.log(a + b);
return (context || this)
},
type: "jQuery"
}))
.then(function({methodName, type}) {
if (type === "jQuery" && methodName in window[type]) {
jQuery[methodName](10, 10)
} else {
if (methodName in window["jQuery"][type]) {
jQuery[type][methodName](10, 10);
}
}
})
.catch(function(err) {
console.error(err)
});
});
$(function() {
Promise.resolve($.addMethod({
methodName: "add",
method: function add(a, b, context) {
console.log(a + b);
return (context || this)
},
type: "fn"
}))
.then(function({methodName, type}) {
if (methodName === "jQuery" && methodName in window[type]) {
jQuery[methodName](10, 10)
} else {
if (methodName in window["jQuery"][type]) {
jQuery("span")[methodName](10, 10);
}
}
})
.catch(function(err) {
console.error(err)
});
});
$(function() {
Promise.resolve(
$.addMethod({
methodName: "reverseText",
method: function reverseText(_text, context) {
let text = [...(_text || this.text())].reverse().join("");
(context || this).text(text);
return (context || this)
},
type: "fn"
}))
.then(function({methodName, type}) {
if (type === "jQuery" && methodName in window[type]) {
jQuery[methodName]()
} else {
if (methodName in window["jQuery"][type]) {
// set context `this` to `span`
let span = jQuery("section")[methodName]("321", $("span"))
.css("color", "sienna");
console.log(
span.is(document.querySelector("span"))
);
jQuery("section")[methodName]()
.css("color", "green");
}
}
})
.catch(function(err) {
console.error(err)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<section>section</section>
<span>span</span>

Can't enumerate getters/setters properties

I am working on some reflections code to try to scrape out properties and functions, but I can't seem to get the getters/setters at all.
The reflection code I have for properties is:
Reflector = function() { };
Reflector.getProperties = function(obj) {
var properties = [];
var proto = obj;
while (proto != Object.prototype) {
console.log('Scrapping proto: ', proto);
for (var prop in proto) {
console.log('typeof ' + prop + ": ", typeof obj[prop]);
if (typeof obj[prop] != 'function') {
properties.push(prop);
}
}
proto = Object.getPrototypeOf(proto);
}
return properties;
};
And a sample of it running (with my debug messages) is:
var SimpleTestObject = function() {
this.value = "Test1";
this._hiddenVal = "Test2";
this._readOnlyVal = "Test3";
this._rwVal = "Test4";
};
SimpleTestObject.prototype = {
get readOnlyVal() {
return this._readOnlyVal;
},
get rwVal() {
return this._rwVal;
},
set rwVal(value) {
this._rwVal = value;
},
func1: function() {
// Test
}
};
SimpleTestObject.func2 = function(test) { /* Test */ };
SimpleTestObject.outsideVal = "Test5";
var props = Reflector.getProperties(SimpleTestObject);
console.log('props: ', props);
console.log('Object.getOwnPropertyNames: ', Object.getOwnPropertyNames(SimpleTestObject));
console.log('rwVal property descriptor: ', Object.getOwnPropertyDescriptor(SimpleTestObject, 'rwVal'));
console.log('rwVal (2) property descriptor: ', Object.getOwnPropertyDescriptor(Object.getPrototypeOf(SimpleTestObject), 'rwVal'));
What I expect to see as output to my Reflection.getProperties(SimpleTestObject) is ['readOnlyVal', 'rwVal', 'outsideVal'], but instead I am only seeing outsideVal. Further, when I tried to using getOwnPropertyDescriptor() to see if the rwVal was enumerable, it came back as undefined. So, thinking maybe it somehow got showed into the prototype above, I tried going up a level and still got undefined.
For enumerate the getters please use Object.keys or Object.getOwnPropertiesNames on prototype instead of constructor or/and instance:
function readGetters(obj) {
var result = [];
Object.keys(obj).forEach((property) => {
var descriptor = Object.getOwnPropertyDescriptor(obj, property);
if (typeof descriptor.get === 'function') {
result.push(property);
}
});
return result;
}
var SimpleTestObject = function() {
this.value = "Test1";
this._hiddenVal = "Test2";
this._readOnlyVal = "Test3";
this._rwVal = "Test4";
};
SimpleTestObject.prototype = {
get readOnlyVal() {
return this._readOnlyVal;
},
get rwVal() {
return this._rwVal;
},
set rwVal(value) {
this._rwVal = value;
},
func1: function() {
}
};
SimpleTestObject.func2 = function(test) { /* Test */ };
SimpleTestObject.outsideVal = "Test5";
// For constructor
console.log(readGetters(SimpleTestObject.prototype));
// For instance
var instance = new SimpleTestObject();
console.log(readGetters(Object.getPrototypeOf(instance)));
you can enumerate setter/getter properties by Object.getOwnPropertyNames if you use getter and setter with Object.defineProperty or Object.defineProperties
const _name = Symbol();
const _age = Symbol();
class Dog {
constructor(name, age) {
Object.defineProperties(this, {
name: {
// you can set enumerable true explicitly if you want
//enumerable:true ,
set(value) {
this[_name] = name;
},
get() {
return this[_name];
}
},
age: {
set(value) {
this[_age] = age;
},
get() {
return this[_age];
}
},
book: {
get() {
return "Book"
}
}
});
this.name = name;
this.age = age;
}
}
const dog = new Dog("spike", 3);
console.log(Object.getOwnPropertyNames(dog));

Copy object properties in JavaScript

I have some custom Object definitions like:
var Class1 = function () { this.value = ''; };
var Class2 = function () { this.data = ''; };
Class1.prototype = {
setObject: function () {
for (var prop in this){
if (typeof obj[prop] != 'undefined')
this[prop] = obj[prop];
}
}
}
Class2.prototype = {
setObject: function () {
for (var prop in this){
if (typeof obj[prop] != 'undefined')
this[prop] = obj[prop];
}
}
}
Is there a way to have this method setObject by default to all clases?
Is it better to (simulate) inherit that function from the Object type in JavaScript or is it better to use a global function or to define it one by one?
If you're going to be using a library such as jQuery or underscore, you'll already have access to a resilient extend method (see $.extend, and _.extend), so I would say that there's no reason to reinvent the wheel on these custom object types.
Otherwise, you can have Class1 and Class2 inherit from a common base class:
function BaseClass() {
...
}
BaseClass.prototype = {
setObject: function (obj) {...}
};
function Class1() {
...
}
Class1.prototype = new BaseClass();
function Class2() {
...
}
Class2.prototype = new BaseClass();
var a = new Class1();
a.setObject({...});
var b = new Class2();
b.setObject({...});
Or, if those objects should not contain a common ancestor, you could define them to use the same setObject function reference:
function setObject(obj) {
...
}
function Class1() {
...
}
Class1.prototype = {
setObject: setObject
};
function Class2() {
...
}
Class2.prototype = {
setObject: setObject
}
I am not sure if you know that, but there are no classes or methods in Javascript. There are only objects, functions and a special property called "prototype".
The common way of simulating classes is this:
var Class = function () { this.prop = "hi" };
Class.prototype.doMethod = function () { this.prop = "hi2"; };
Class.prototype.setObject: function () {
for (var prop in this){
if (typeof obj[prop] != 'undefined')
this[prop] = obj[prop];
}
}
// those classes "inherit" from Class
var Class1 = function () { Class.call(this); this.value = ''; };
Class1.prototype = new Class();
var Class2 = function () { Class.call(this); this.data = ''; };
Class2.prototype = new Class();
Ivan showed how to inherit from an object. More information about using constructor functions and inherritance can be found here: Prototypical inheritance - writing up
You can use a mixin pattern as well:
var mixIn=function(target,source){
for(fn in source){
if(source.hasOwnProperty(fn)){
target.prototype[fn]=source[fn];
}
}
};
var ObjectSettable = {
setObject: function () {
for (var prop in this){
if (typeof obj[prop] != 'undefined')
this[prop] = obj[prop];
}
}
};
var Class1 = function () { this.value = ''; };
//... Class1.prototype stuff
mixIn(Class1,ObjectSettable);

Why is this prototype failing?

function _(e) {
if (typeof e == 'string') {
if (e.charAt(0) == '#') {
return document.getElementById(e.slice(1));
} else if (e.charAt(0) == '.') {
var c = document.getElementsByClassName(e.slice(1));
return (c.length==1)?c[0]:c;
} else {
var t = document.getElementsByTagName(e);
return (t.length==1)?t[0]:t;
}
} else {
console.log('Error. Not a valid string in _.');
}
}
_.prototype.hide = function() {
//testing
console.log(this)
}
The function works fine, but when i try to add the method hide and try and call it like _('#menu').hide();, it throws the error: TypeError: Object #<HTMLDivElement> has no method 'hide' What have I misunderstood?
And yes, I did google this problem, I just don't get it. A hint would be much appreciated.
The constructor function needs to return itself (return this;). Currently it returns a DOM object, or undefined if no string is passed.
Try this:
function _(e) {
if (!(this instanceof _)){
return new _(e);
}
if (typeof e == 'string') {
if (e.charAt(0) == '#') {
this.el = document.getElementById(e.slice(1));
} else if (e.charAt(0) == '.') {
var c = document.getElementsByClassName(e.slice(1));
this.el = (c.length==1)?c[0]:c;
} else {
var t = document.getElementsByTagName(e);
this.el = (t.length==1)?t[0]:t;
}
return this;
} else {
console.log('Error. Not a valid string in _.');
throw e + ' is not a valid string';
}
}
_.prototype.hide = function() {
console.log(this);
}
You can invoke the constructor like so:
e = _('#myDiv');
e.hide();
You use a constructor function as a regular function, so it won't create an object, it will just return what you specified.
You can use it as a regular function, but then you need to call itself as a constructor to create the object to return, and handle when it's used as a constructor:
function _(e) {
if (!this instanceof _) {
if (typeof e == 'string') {
if (e.charAt(0) == '#') {
return new _(document.getElementById(e.slice(1)));
} else if (e.charAt(0) == '.') {
var c = document.getElementsByClassName(e.slice(1));
return new _((c.length==1)?c[0]:c);
} else {
var t = document.getElementsByTagName(e);
return new _((t.length==1)?t[0]:t);
}
} else {
console.log('Error. Not a valid string in _.');
}
} else {
this.elements = e;
}
}
You might consider to always use an array for the elements, even when it's a single element. Right now the elements property will either be an element or an array of elements, so you have to check for this every time you use it...
Try to define your function like this:
var _ = function (e) { };
EDIT
And yes don't forget to return this of course.

Categories

Resources