如何通过在节点

时间:2016-04-10 19:06:40

标签: javascript arrays node.js object

在一个脚本中,我有一个包含其他几个对象的对象,它们都具有相同的结构。它看起来像这样:

wordlist = {word1: {count:2},
word2: {count:5},
word3: {count:3},
word4: {count:2}}

我想生成一个只包含每个单词计数的数组,所以它看起来像[2,5,3,2]。

在Node.js中有没有办法做到这一点?

我会想象使用for循环,每次迭代都转到下一个子对象,但是如何通过它在主对象中的位置来选择子对象? 在数组中,您可以键入arrayName [2]来获取该数组中的第三个条目,对象是否可能类似?

2 个答案:

答案 0 :(得分: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>');
 

ES6版本

var wordlist = { word1: { count: 2 }, word2: { count: 5 }, word3: { count: 3 }, word4: { count: 2 } },
    result = Object.keys(wordlist).map(k => wordlist[k].count);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
 

答案 1 :(得分:0)

使用loadash

执行此操作的另一种方法

_。map(wordlist,function(a){return a.count;})