0

Let's say I have a object from a class that contains methods and properties like so:

function Fruit (type, color) {
    this.type = type;
    this.color = color;
    this.getInfo = function() {
        return this.color + ' ' + this.type;
    };
    this.loadJSON = function() {
        //TODO
    };
}

var red_apple = new Fruit ('apple', 'red');

I want to load new data from JSON like:

red_apple.loadJSON( '{"new_apple": {"color": "green", "type": "apple"}}' );

How would I implement this.loadJSON? Is there a standard function?

Simon
  • 4,395
  • 8
  • 33
  • 50

2 Answers2

1

Try this:

this.loadJSON = function(json) {
    //TODO
    var jsonFruit = JSON.parse(json);

    this.color = jsonFruit.new_apple.color;
    this.type = jsonFruit.new_apple.type;
};
brso05
  • 13,142
  • 2
  • 21
  • 40
  • is that putting the values onto an existing object or creating a new object? – dandavis Mar 30 '15 at 15:57
  • @brso05 He already has that method called `this.loadJSON` and needs just the implementation – Mohamed Shaaban Mar 30 '15 at 16:03
  • @mshaaban is totally right. The problem was not about parsing a JSON string into an JSON object. I would've mentioned that. – Simon Mar 30 '15 at 16:05
  • @brso05 Question's title is `Loading only properties from JSON into existing javascript object **without destroying methods**` – Mohamed Shaaban Mar 30 '15 at 16:07
  • Here's a function which will copy all variables that don't exist in the destination object. http://jsfiddle.net/76pmu4ou/ – Domino Mar 30 '15 at 16:24
1

Try jQuery extend function

function Fruit (type, color) {
    this.type = type;
    this.color = color;
    this.getInfo = function() {
        return this.color + ' ' + this.type;
    };
    this.loadJSON = function(json) {
        //TODO
        var jsonFruit = JSON.parse(json);

        $.extend(this, jsonFruit.new_apple);
    };
}

var red_apple = new Fruit ('apple', 'red');

console.log(red_apple.getInfo()); // Prints "red apple"

red_apple.loadJSON( '{"new_apple": {"color": "green", "type": "apple"}}' );

console.log(red_apple.getInfo()); // Prints "green apple"
Mohamed Shaaban
  • 1,129
  • 6
  • 13