gpt4 book ai didi

javascript - 如何通过对象在Node中另一个对象中的位置从对象中获取值

转载 作者:行者123 更新时间:2023-11-29 21:30:51 25 4
gpt4 key购买 nike

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

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

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

在 Node.js 中有什么方法可以做到这一点吗?

我会想象使用 for 循环,每次迭代都转到下一个子对象,但我如何根据子对象在主对象中的位置来选择它?在一个数组中,您可以键入 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>');

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>');

关于javascript - 如何通过对象在Node中另一个对象中的位置从对象中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com