user2713706
user2713706

Reputation: 147

Creating Objects inside objects using a Constructor

In the below code I am trying to create an object named "portfolio" inside which I want to create other objects that contain the properties "stockvalue" and "price"?

var portfolio_create = function(stock,stockvalue,price)
{
    for(i in stock)
    {
        this[stock[i]] = stock[i];
        this[stock[i]]["stockvalue"] =stockvalue[i];
        this[stock[i]]["price"]=price[i]    
    }
}

var portfolio = new portfolio_create(["ibm","tcs"],[23,34],[34,45]);

var stock_market = portfolio;


alert(portfolio["ibm"]["stockvalue"]);  // undefined

Why does the alert return "undefined" and not 23?

Thnaks in advance.

Upvotes: 0

Views: 81

Answers (3)

dec
dec

Reputation: 604

And try to use libs like underscore or lodash to get rid of these for loops (each). It is much nicer and more functional.

A little bit shorter:

this[stock[i]] = { stockvalue: stockvalue[i], price: price[i] };

Upvotes: 1

S. Dess
S. Dess

Reputation: 11

I think there is a little confusion here, between objects and variables.

You can create a real JavaScript class portfolio, which contain a collection of another class stock, which contain 2 variables value and price.

In your portfolio class, you can add a AddStock methode, and a GetStock.

Look at JavaScript Classes, I think you will find your hapiness.

Steeve

Upvotes: 1

Oleksandr T.
Oleksandr T.

Reputation: 77482

var portfolio_create = function (stock, stockvalue, price) {

    for (var i = 0, len = stock.length; i < len; i++) {
        this[stock[i]] = {};

        this[stock[i]]["stockvalue"] = stockvalue[i];
        this[stock[i]]["price"]      = price[i];    
    }
}
var portfolio = new portfolio_create(["ibm", "tcs"], [23,34], [34,45]);
  1. Don't use for..in for arrays.
  2. this[stock[i]] = stock[i]; replace to this[stock[i]] = {};.

Example

Upvotes: 1

Related Questions