【问题标题】:How to get a value from an object by its position in another object in Node如何通过对象在Node中另一个对象中的位置从对象中获取值
【发布时间】:2016-07-31 18:18:49
【问题描述】:

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

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

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

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

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

【问题讨论】:

标签: javascript arrays node.js object


【解决方案1】:

您可以遍历适当对象的键并映射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>');
 

【讨论】:

    【解决方案2】:

    使用 loadash 的另一种方法

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

    【讨论】:

      猜你喜欢
      • 2021-10-18
      • 2021-11-09
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多