Reputation: 1819
Can An Array Be Added to Object? I have defined 2 Arrays itemId and itemName and pushed some values in them. Can these 2 arrays be pushed or be a part of ItemCatalog Object?
var ItemCatalog = new Object();
itemId = new Array();
itemName = new Array()
/*
var itemId = new Array();
var itemName = new Array();
*/
var currentItemIndex = 5;
itemId.push(1);
itemId.push(2);
itemId.push(3);
itemId.push(4);
itemId.push(5);
itemId.push(6);
itemId.push(7);
itemId.push(8);
itemId.push(9);
itemId.push(10);
itemName.push("A");
itemName.push("B");
itemName.push("C");
itemName.push("D");
itemName.push("E");
itemName.push("F");
itemName.push("G");
itemName.push("H");
itemName.push("I");
itemName.push("J");
Thanks, Ankit
Upvotes: 2
Views: 107
Reputation: 98816
Yes. Continuing the code you've posted:
ItemCatalog.itemId = itemId;
ItemCatalog.itemName = itemName;
However, you can do this at the same time as creating the array, which saves cluttering up your current scope with an unnecessary variable:
var ItemCatalog = new Object();
ItemCatalog.itemId = new Array();
ItemCatalog.itemName = new Array();
ItemCatalog.itemId.push(1);
...
ItemCatalog.itemName.push("A");
...
Note also that by convention in JavaScript, names starting with a capital letter are used for constructor functions rather than objects. (At least according to Douglas Crockford.)
So this would be more idiomatic:
var itemCatalog = new Object();
Upvotes: 0
Reputation: 72857
Yes, you can:
var itemId = [1,2,3,4,5,6,7,8,9,10];
var itemName = ["A","B","C","D","E","F","G","H","I","J"];
var currentItemIndex = 5;
var ItemCatalog = {
itemIds: itemId,
itemNames: itemName
};
Another way to assign variables to your object would be:
var ItemCatalog = {}
// or like you did: var ItemCatalog = new Object(); That's the same as = {}
// Then:
ItemCatalog.itemIds = itemId;
// Or
ItemCatalog['itemNames'] = itemName;
Notice how I replaced your object / array initialisations with object / array literals. Both work, but I prefer the literals, since they're shorter.
Upvotes: 4
Reputation: 337570
You can just assign the arrays as values of properties of the object, like this:
// setup arrays here...
var itemCatalog = {
itemId: itemId;
itemNames: itemName
};
However if id
and name
are associated, why not add them in a single array? Something like this:
items = [];
items.push({ id: 1, name: 'A' });
items.push({ id: 2, name: 'B' });
console.log(items[0].name); // = A
Upvotes: 0
Reputation: 388316
yes
var ItemCatalog = {
itemId : itemId,
itemName : itemName
}
Upvotes: 1