GibboK
GibboK

Reputation: 73908

How to create properties to and object dynamically based on another object in JavaScript?

I have a scenario where from a source object I need to create a new result object.

The object would need to have exactly all properties from source, with the addition of "methods", with naming based on the properties and code to be executed based on a template (in my case alert(this.x)).

Note: script should keep in consideration any number of properties from source

I would like to know:

FROM SOURCE OBJECT

  var source = {
        a: 'a',
        b: 'b'
    };

I NEED TO GET RESULT OBJ DYNAMICALLY CREATED (BY SOME FUNCTION)

    var result = {
        a: 'a',
        b: 'b',
        _setA: function(){
            alert(this.a);
        },
        _setB: function(){
            alert(this.a);
        }
    }

Note: result is created after processing the source object

EDIT:

final solution based on your answers

http://jsfiddle.net/kbnd6e5c/1/

Upvotes: 1

Views: 44

Answers (3)

dfsq
dfsq

Reputation: 193261

You can first use $.extend method to copy properties, and then you need iterate through properties and create dynamic setters. For example like in below code:

var source = { a: 'a', b: 'b' };    
var result = $.extend({}, source);

Object.keys(source).forEach(function(key) {
    result['_set' + key[0].toUpperCase() + key.slice(1)] = function(value) {
        alert(this.key);
        this[key] = value;
    }
});

Check the working demo below.

var source = { a: 'a', b: 'b', test: 'test' };    
var result = $.extend({}, source);
    
Object.keys(source).forEach(function(key) {
    result['_set' + key[0].toUpperCase() + key.slice(1)] = function(value) {
        this[key] = value;
    }
});

alert([ result.a, result.test ]);

result._setA('a1');
result._setTest('test1');

alert([ result.a, result.test ]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Sergio Flores
Sergio Flores

Reputation: 5427

You can do something like this:

var result = {
    a: 'A',
    b: 'B'
};

var copy = result;

Object.keys(result).forEach(function(key) {
    Object.defineProperty(copy, "_set" + key, {
        get: function() {
            return result[key]; 
        }
    })
});

copy._seta;
copy._setb;

Source

Upvotes: 0

TotuDoum
TotuDoum

Reputation: 137

I'm not sure I have fully understanding your question but I think you should juste use that simple thing:

var copy = result
copy.example = {
    x: Y,
    z, T
}
copy.newFuntion = function(){...} //add your own function

This way you have everything that result have + your own things

Upvotes: 0

Related Questions