如何声明数组的哈希/字典

时间:2017-03-08 23:04:01

标签: javascript arrays dictionary

我有一个程序将值推送到一个数据结构中:

if(symbolType == "C" || symbolType == "P") // The calls and puts               
    stocks.push({                    
        symbol: symbol,
                undsymbol: undSymbol,
                open: 0,
                type: symbolType,
                expiry: expiry,
                days: days,
                strike: strike

    });
}            
else  // The stock     
{           
    stocks.push({
        symbol: symbol,
        open: 0,
        type: symbolType
    });
}

所以这是关键:不是一个字符串!

{
    symbol: symbol,
    open: 0,
    type: symbolType
}

其中许多值看起来像这样:

{                    
        symbol: symbol,
                undsymbol: undSymbol,
                open: 0,
                type: symbolType,
                expiry: expiry,
                days: days,
                strike: strike

 }

问题在于股票,看涨期权和看跌期权被放入一个集合中。相反,我想添加股票及其相应的看涨期权并放入字典/地图中,其中股票是关键字,而看涨期权和看跌期权被推入由其股票编制索引的数组中。

最后,我希望能够迭代并获取键和值。

  • 如何声明此对象
  • 索引到它以查看密钥[stock]是否已经存在,如果它没有用空数组添加它。
  • 如果我得到一个" C"或者" P",我想获得相应的数组,其中包含此键[stock]的Calls / Puts并将call / put推入数组。

最初我认为宣言是这样的:

var stockCallsPutDict = {[]}


stockCallsPutDict[stock] = [];
stockCallsPut[stock].push(call);

// Pretty print the dict of keys and its options =
stockCallsPutDict.forEach(function kvp) {
   ...
}

3 个答案:

答案 0 :(得分:2)

如果ES6是一个选项,您可以自己构建一个对象,也可以使用Map

这是我提出的一些快速代码:

const stocks = {};
const addCallAndPut = callAndPut => {
  const symbol = callAndPut.symbol;
  if (!stocks[symbol]) {
    stocks[symbol] = [];
  }
  stocks[symbol].push(callAndPut);
}

const showStuff = () => {
  for (const symbol in stocks) {
    // output stuff using stocks[symbol]
  }
}

或使用地图

const stocks = new Map();

// basic implementation 
const addCallAndPut = callAndPut => {
  const stockCallsAndPuts = stocks.get(callAndPut.symbol) || [];
  stockCallsAndPuts.push(callAndPut);
  stock.set(callAndPut.symbol, stockCallsAndPuts);
}

答案 1 :(得分:0)

有几种方法可以解决这个问题,最好的方法取决于以后需要处理数据的方式,但从您的描述中我可以选择

var stocks = {};
var stockCallsPut = {};

// loop over stocks and actions
    if (!(symbol in stocks)) {
      stocks[symbol] = [];
    }

    if (!(symbol in stockCallsPut)) {
      stockCallsPut[symbol] = {};
    }

    if (!(symbolType in stockCallsPut[symbol])) {
        stockCallsPut[symbol][symbolType] = [];
    }

    // accumulated stock json items here
    stocks[symbol].push(new_stock_item);
    // accumulated push/call json items of stock here 
    stockCallsPut[symbol][symbolType].push(new_action);

答案 2 :(得分:0)

我仍然不确定我是否真正了解您的数据是什么样的,但听起来有点像这样:

// Not sure if data is an object or array
var data = {
  'one': {
    'name': 'one-somename',
    'number': 'one-somenumber',
    'symbol': 'C'
  },
  'two': {
    'name': 'two-somename',
    'number': 'two-somenumber',
    'symbol': 'P'
  },
  'three': {
    'name': 'three-somename',
    'number': 'three-somenumber',
    'symbol': 'C'
  }  
};

var stocks = {};

for (var name in data) {
  // It sounded like you wanted a call/put array for each object but I'm not sure if that's true since it wouldn't be possible... if so can just divide this part up into it's appropriate place in the if statement below

  // Checking that the property is set on the object, if it is, it uses itself, otherwise it adds it with the call/put arrays created
  stocks[name] = stocks[name] ? stocks[name] : {'calls': [], 'puts': []};
  var type;

  if (data[name]['symbol'] === 'C') {
    type = 'calls';
  } else if (data[name]['symbol'] === 'P') {
    type = 'puts';
  }

  stocks[name][type].push(data[name]);
}