WG-
WG-

Reputation: 1070

Access data of associative array inside associative array

Is it possible to access data of an associative array inside an associative array?

For instance,

foo = {
  subFooA: 2,
  subFooB: subFooA
}

or

foo = {
  subFooA: 2
}

foo = {
  subFooB: subFooA
}

-Edit- Thank you for the answers... so I assume it is not possible for this

filter = {
    leadlag: {
        parameters: {
            K: 1,
            fz: 20,
            fp: 40,
            wz: 2*math.pi*20,
            wp: 2*math.pi*40
        }
    }
}

filter.leadlag.continuous = {
    a: [filter.leadlag.parameters.K*filter.leadlag.parameters.wp*filter.leadlag.parameters.wz, filter.leadlag.parameters.K*filter.leadlag.parameters.wp],
    b: [filter.leadlag.parameters.wp*filter.leadlag.parameters.wz, filter.leadlag.parameters.wz]
}

to be done more easily?

Upvotes: 1

Views: 69

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386560

Answer to your question v 2.0:

Yes it is possible and readable with a helper variable which holds the reference to the object.

var filter = {
        leadlag: {
            parameters: {
                K: 1,
                fz: 20,
                fp: 40,
                wz: 2 * Math.PI * 20,
                wp: 2 * Math.PI * 40
            }
        }
    },
    p = filter.leadlag.parameters; // helper variable for better accessing

filter.leadlag.continuous = {
    a: [p.K *  p.wp * p.wz, p.K * p.wp],
    b: [p.wp * p.wz,  p.wz]
}
document.write('<pre>' + JSON.stringify(filter, 0, 4) + '</pre>');

Upvotes: 1

vorillaz
vorillaz

Reputation: 6266

Yes it is possible, you may follow different patterns as well:

var foo = {}
foo.subFooB = foo.subFooA = 2;

I always prefer using setter functions though as a cleaner approach:

function setFoo() {
  return 2;
}
var foo = {
  subfooA: setFoo(),
  subFooB: setFoo()
}

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

The first is not possible, while with the second you were almost there:

var foo = {
    subFooA: 2
};

foo.subFooB = foo.subFooA;

Upvotes: 0

Related Questions