0

How do I access the stocks variable from inside broadcast

var net = require('net');
var ReadWriteLock = require('rwlock');

var stocks = [
    {symbol: "GM", open: 48.37},
    {symbol: "GE", open: 29.50}
];

var server = net.createServer(function(socket) {
    // Handle incoming messages from clients.
    socket.on('data', function (data) {
        broadcast(data, socket);
    });

    function broadcast(message, sender) {
        lock.readLock(function (release) {
            ....
            maxChange = 100.0 * 0.005;
            change = (maxChange - Math.random() * maxChange * 2);

            stock = stocks[symbol],
            maxChange = stock.open * 0.005,
            ....
           //**How do I access stocks  from here?**
        });

        release();
    });    
 }

Gives error:

  maxChange = stock.open * 0.005,                                 ^
  TypeError: Cannot read property 'open' of undefined
Ivan
  • 7,448
  • 14
  • 69
  • 134
  • 1
    I don't think `stock = stocks[symbol]` will work the way you're expecting, you may be looking for this: http://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects – DBS Feb 08 '17 at 00:37
  • You've declared `stocks` as an array, it has numerical indices. What is `stocks[symbol]` supposed to be? Because `symbol` better be a number. If it isn't, this code will never get anything out of the stocks array. – Mike 'Pomax' Kamermans Feb 08 '17 at 00:41
  • Ugh, Stupid question. Sorry. I thought it had to do with namespaces and globals. I didn't realize I had a bug. – Ivan Feb 08 '17 at 00:41

1 Answers1

1

Your code implies that symbol is a key of the array, but it is not. It is a property in one of the objects in the array.
Use this:

Array.prototype.myFind = function(obj) {
    return this.filter(function(item) {
        for (var prop in obj){
            if (!(prop in item) || obj[prop] !== item[prop]){
                 return false;
            }
        }
        return true;
    });
};
// then use:
var arrayFound = stocks.myFind({'symbol':symbol});

This will find the array element where the symbol property of the object is equal to the variable symbol
Found here

Community
  • 1
  • 1