0

I am trying to build an array of objects in javascript. Somehow I have not found the answer I am looking for anywhere. Yes I did search questions.

So a traditional object has properties obviously such as:

item being the object

item = new Object();

with properties and methods

item.name = "sword"; // "sword" being the string name of the object
item.buy = buy; //buy being a function to add said item

that's just great and I get that.

I get arrays too.

My question is, if I want say 20 of those objects, how could i make them in an array instead of making many objects

example, I know I can do this.

item1 = new Object();
item1.name = "sword";
item1.buy = buy;

item2 = new Object();
item2.name = "shield";
item2.buy = buy;

However, I would like to do something like this

item = new Array();
item[0].name = "sword";
item[0].buy = buy;

item[1].name = "shield";
item[1].buy = buy;

Maybe it's obvious, but I'm not getting what's wrong here.

When i attempt to call

item[0].buy(); 

I encounter the error "Uncaught TypeError: Object 0 has no method 'buy' " and item[0].name is undefined.

What am I doing wrong and how do I go about this?

7 Answers 7

4

My guess is that what you want is an array of objects:

var item = new Array();
item[0] = {};
item[0].name = "sword";
item[0].buy = function() { return this.name };
item[0].buy();
// -> "sword"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I figured this out about 2 minutes after posting the question. I had thought that everything being an object, that array elements were as well but did not realize that they only are when initialized as such.
2
// create a new array
var items = [];

// You can push objects onto the array as literals like this
items.push({
 name: "sword",
 buy: buy
});

// Or you can create the new object as you're doing currently    
var item = new Object();
item.name = "shield";
item.buy = buy;

// And push it onto the array as before
items.push(item);

// Now you can access each object by it's index in the array 
items[0].buy();
console.log(items[1].name); // "shield"

1 Comment

This is also a good solution. I like my code to be as concise as possible though. Thanks for the input!
0

You can use literals like this:

var items = [{
  name: '1',
  buy: buy
}, {
  name: '2',
  buy: buy
}, {
  name: '3',
  buy: buy
}];

But I would consider using prototypes since buy is a shared method:

function Item(name) {
  this.name = name;
}

Item.prototype.buy = function() {
  ...
};

var items = [
  new Item('1'),
  new Item('2'),
  new Item('3')
];

items[1].buy();

Comments

0

Can simplify the syntax down to:

var arr=[
    {name:'foo',age:49},
    {name:'GG', age:12},
    {name:'MMMM', age:16}
];

All depends what your overall goal is.

Using var xyz={} is same as writing out new Object() simlarly for [] to start a new array

Comments

0

You can create a function called Item that will return an object with the name property, then use prototype to attach a method to it. Although JavaScript does not have classes, this will behave similar to it.

function Item(name) {
    this.name = name
}

Item.prototype.buy = function() {
    // your code to buy an item
    // you can access your item's name property here by using this.name
    alert("You bought the item " + this.name)
}

Then, you can instantiate this function and add the returned objects to an array:

var items = []
items.push(new Item('sword'))
items.push(new Item('shield'))
items[0].buy() // will buy the item "sword"
items[1].buy() // will but the item "shield"

Comments

0

looks as though you didn't add the items to your array via items.push(item1)

item1 = {};
item2 = {};

item1.name = "a";
item2.name = "b";

var buy = function() { console.log('buying... '+this.name); };

item1.buy = buy;
item2.buy = buy;

var items = [];

items.push(item1);
items.push(item2);
items[0].buy();

Comments

0

Because, you didn't create any object at the 0 index of your array and buy should be a function

item = new Array();
// create an object at 0/first index of array which is equivalent of new Object
item[0] = {};
// create property 'name' and assign value ("sword") to it
item[0].name = "sword";
// create another property and assign a function as it's value
// so buy is a method of the first object that is in in the item array
item[0].buy = function(){
    return 'buy called';
};
// call 'buy' method from the first object of item array
console.log(item[0].buy());

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.