Reputation: 147
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
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
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
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]);
for..in
for arrays. this[stock[i]] = stock[i];
replace to this[stock[i]] = {};.
Upvotes: 1