1

I'm learning to use key/value arrays and object/properties.

I have an arrayList of items.

var itemList = [firstitem, seconditem];

How do I give each itemList properties?

itemList[0].name = "pear";
itemList[0].value = "$5";

Is this correct?

var items = [ 
      { 
          "name": "pear",
          "value": "$2"
      }, {
          "name": "apple",
          "value": "$5"
      }];
2
  • 2
    looks perfectly all right. Commented Dec 29, 2014 at 17:38
  • Just paste it in your Browser Console then print the value of items. Commented Dec 29, 2014 at 17:39

2 Answers 2

3

That’s the most common way if you want to initialize an array with predefined objects as items. You could also do it like this:

var items = [];
items[0] = {
    "name": "pear",
    "value": "$2"
};
items[1] = …

or

var items = [];
items[0] = {};
items[0].name = "pear";
items[0].value = "$2";

items[1] = …
Sign up to request clarification or add additional context in comments.

Comments

2

Well here is http://jsfiddle.net/coolbhushans/3ubhnedm/ the js fiddle of the same

var items = [ 
      { 
          "name": "pear",
          "value": "$2"
      }, {
          "name": "apple",
          "value": "$5"
      }];

alert("1st name "+items[0].name +"\t second name " +items[1].name);
alert("1st value "+items[0].value+ "\t second value"+ items[1].value );

Comments

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.