Reputation: 803
I am from a classical OOO background and finding it difficult to understand the javascript object literal construction. I need a javascript variable containing an array of name value pairs. I should be able to push name, value pairs to the array through a function. SOmehow, I am finding it confusing to create such data structure. Could you please help me know the correct syntax for the same:
What I am looking for
var selectedItemArray = array of name, value pairs
and i should be able to
selectedItemArray.push(name, value);
and
selectedItemArray.get(index);
var tagArray = [];
for (var i in secondaryTagsArray) {
tagArray.push({tagId:secondaryTagsArray[i].secondary_tag_id,
tagName:secondaryTagsArray[i].secondary_tag_name
});
}
Upvotes: 1
Views: 97
Reputation: 239473
Key-Value pairs can be created with JavaScript Objects, with Object lietral, like this
{key: value}
Arrays can be created with Array literal ([]
) or with Array
constructor like this
new Array(size);
You can use both of them, like this
var array = [];
array.push({key1: value1});
Since JavaScript arrays begin with index 0, you need to access the first element with index 0, second with 1 and so on.
console.log(array[0]);
will print the first key-value pair stored at index 0.
Upvotes: 1