0

I have an object like that:

vm.data = {
        a : {
            v : 25
        },
        b : {
            v : "",
            c : "f + a"
        },
        c : {
            v : "",
            c : "b + a"
        },
        d : {
            v : "",
            c : "c + e"
        },
        e : {
            v : "",
            c : "a + c"
        },
        f : {
            v : "",
            c : "b + c"
        }
    };

and I would like to have all these calculations done every time I change A. I cannot find a solution to solve this problem. Any idea?

PS: this is just an simple example of an object hundreds time bigger and complicated than this.

3
  • why not use some function or getters? Commented Mar 7, 2017 at 20:30
  • do you have stored in some place which change triggers which calculations ? or are they harcoded in code or something ? Commented Mar 7, 2017 at 20:30
  • @NinaScholz: can you give an example of a getter please? Gonzalo.- : I've got a service with this data and I've to calculate all these values every time I change one of them (in this case only A). Commented Mar 7, 2017 at 20:34

1 Answer 1

2

You could use a getter method for getting an actual value of the calculation of the properties.

var object = {
        a: 6,
        b: 42,
        get c() { 
            return this.a + this.b;
        }
    };
    
console.log(object.c);
object.a = 1000;
console.log(object.c);

var object = {
        a : 25,
        get b () { return this.a * 5; },
        get c () { return this.b + this.a; },
        get d () { return this.c + this.a; }
    }; 
    
console.log(object.d);
object.a = 1000;
console.log(object.d);

Sign up to request clarification or add additional context in comments.

3 Comments

it's a very good solution and it works well...I have just to find a way to change my original object in this way. The biggest problem is that I have to use parseInt to get numbers, otherwise it sees the values like strings. Thank you. PS: Any other suggestion is very welcome (I would like avoid to change the original object)!
PSS: it works in this way: vm.data = { a : 25, get b () { return this.a * 5 }, get c () { return parseInt(this.b) + parseInt(this.a) }, get d () { return parseInt(this.c) + parseInt(this.a) } }; but it doesn't work if, in c, a change this.b with this.d because d is calculated afterwards (I presume) ...and I have scenarios like that unfortunately.
you need the right order and prevent circular references.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.