1

Is there a way to initialize a javascript object with an array of child objects in one line? How can I do the following in just on initialization line.

var obj = {doc: 100,
           defaultrateid: 32,
           rates: [],
          };
obj.rates[31] = {rate: 101.00, name: "Rate 1"};
obj.rates[32] = {rate: 121.00, name: "Rate 2"};

Basically what I want is a single javascript object that has my user parameters. This object will be reused on multiple web forms. In the case of 'rates', the forms will have a dropdown to select a rate. The web forms have client side calculations that require the matching rate object based on the rate's unique id (e.g. 32).

I'm trying to use a associative array instead of having to do looping for finding a match based on unique value.

2
  • 1
    Do you mean you actually want it all to fit on one line, or do you just want to initialize the entire object with one statement? Commented Mar 26, 2015 at 18:55
  • I want to initialize the object with one statement. Commented Mar 26, 2015 at 19:28

2 Answers 2

4

Seems a bit hacky:

obj = {
    doc: 100,
    defaultrateid: 32,
    rates: (new Array(30)).concat([{
        rate: 101.00,
        name: "Rate 1"
    }, {
        rate: 121.00,
        name: "Rate 2"
    }])
};

EDIT:

Maybe you don't really need an array, you can use an object like this:

obj = {
    doc: 100,
    defaultrateid: 32,
    rates: {
        "31": {
            rate: 101.00,
            name: "Rate 1"
        },
        "32": {
            rate: 121.00,
            name: "Rate 2"
        }
    }
};

And you can still get the rates like obj.rates[31].

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

Comments

0

Do you mean like this?

var obj = {
  doc: 100,
  defaultrateid: 32,
  rates: [{
    rate: 101.00
  }, {
    rate: 121.00
  }],
};

alert(obj.rates[1].rate);

3 Comments

var obj = {doc: 100, defaultrateid: 32, rates: [{rate: 101.00}, {rate: 121.00} ], }; would be one line
This was my first thought, but OP is creating elements [31] and [32] of the array, not just [0] and [1] as in your example. I'm not sure ATM how to do that myself, just wanted to point it out though.
Thanks for response. I updated my original question to help clarify. I need to find a 'rate' based on a unique id, which is why I am using an associative array.

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.