如何通过在Node中的另一个对象中的位置来获取对象的值
在一个脚本中,我有一个包含其他几个对象的对象,都具有相同的结构。 它看起来像这样:
wordlist = {word1: {count:2}, word2: {count:5}, word3: {count:3}, word4: {count:2}}
我想生成一个数组,每个单词的计数,所以它看起来像[2,5,3,2]。
有什么办法可以在Node.js中做到这一点?
我会想象使用for循环每次迭代到下一个子对象,但我将如何通过它在主对象中的位置来select子对象? 在一个数组中,你可以键入arrayName [2]来获得该数组中的第三个条目,是一个类似的东西可能与一个对象?
您可以迭代适当对象的键并映射count
的值。
var wordlist = { word1: { count: 2 }, word2: { count: 5 }, word3: { count: 3 }, word4: { count: 2 } }, result = Object.keys(wordlist).map(function (k) { return wordlist[k].count; }); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
另一种使用loadash来做到这一点的方法
_.map(wordlist,function(a){return a.count;})