0

In JavaScript I want to create a collection in following way -

Start with an empty collection with var c = [];

Then I want to add item in it; after addition it will look like

{ 'buttonSubmit': function() { /* do some work */ } },
{ 'buttonCancel': function() { /* do some work */ } }

I must add item one by one using loop and records are not json string. I know the push method but problem is it creates indexed array which I don't want to use because I want to retrieve the value from the collection using c['buttonSubmit'] or d.buttonSubmit. I want to avoid looping and compare key name.

Please help me with some simple code example.

1 Answer 1

1

Because you started c as an array, which uses numerical indexes to refer to what's inside it. What you want is to have c as an object, which uses keys to refer to the data inside it.

var c = {};
c.buttonSubmit = function(){...};
c.buttonCancel = function(){...};

//similarly
var c = {
  buttonSubmit : function(){...},
  buttonCancel : function(){...}
}

//using them via dot notation
c.buttonSubmit();
c.buttonCancel();

//using them via bracket notation
c.['buttonSubmit']();
c.['buttonCancel']();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Let me try your solution.
I combined your answer with this code and completed my requirement thanks a lot. var data = { 'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 }; data["PropertyD"] = 4; // dialog box with 4 in it alert(data.PropertyD); alert(data["PropertyD"]);

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.