Javascript 迭代 node.js 中的对象键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7440001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:17:26  来源:igfitidea点击:

Iterate over object keys in node.js

javascriptnode.jsiterator

提问by stewe

Since Javascript 1.7 there is an Iteratorobject, which allows this:

由于 Javascript 1.7 有一个Iterator对象,它允许:

var a={a:1,b:2,c:3};
var it=Iterator(a);

function iterate(){
    try {  
        console.log(it.next());
        setTimeout(iterate,1000);
    }catch (err if err instanceof StopIteration) {  
        console.log("End of record.\n");  
    } catch (err) {  
        console.log("Unknown error: " + err.description + "\n");  
    }  

}
iterate();

is there something like this in node.js ?

node.js 中有这样的东西吗?

Right now i'm using:

现在我正在使用:

function Iterator(o){
    /*var k=[];
    for(var i in o){
        k.push(i);
    }*/
    var k=Object.keys(o);
    return {
        next:function(){
            return k.shift();
        }
    };
}

but that produces a lot of overhead by storing all the object keys in k.

但是通过将所有对象键存储在k.

回答by Raynos

What you want is lazy iteration over an object or array. This is not possible in ES5 (thus not possible in node.js). We will get this eventually.

您想要的是对对象或数组进行延迟迭代。这在 ES5 中是不可能的(因此在 node.js 中是不可能的)。我们最终会得到这个。

The only solution is finding a node module that extends V8 to implement iterators (and probably generators). I couldn't find any implementation. You can look at the spidermonkey source code and try writing it in C++ as a V8 extension.

唯一的解决方案是找到一个扩展 V8 的节点模块来实现迭代器(可能还有生成器)。我找不到任何实现。您可以查看spidermonkey 源代码并尝试用C++ 编写它作为V8 扩展。

You could try the following, however it will also load all the keys into memory

您可以尝试以下操作,但它也会将所有密钥加载到内存中

Object.keys(o).forEach(function(key) {
  var val = o[key];
  logic();
});

However since Object.keysis a native method it may allow for better optimisation.

但是,由于Object.keys是本机方法,因此可以进行更好的优化。

Benchmark

基准

As you can see Object.keys is significantly faster. Whether the actual memory storage is more optimum is a different matter.

正如你所看到的 Object.keys 明显更快。实际的内存存储是否更优化是另一回事。

var async = {};
async.forEach = function(o, cb) {
  var counter = 0,
    keys = Object.keys(o),
    len = keys.length;
  var next = function() {
    if (counter < len) cb(o[keys[counter++]], next);
  };
  next();
};

async.forEach(obj, function(val, next) {
  // do things
  setTimeout(next, 100);
});

回答by amateur barista

Also remember that you can pass a second argument to the .forEach()function specifying the object to use as the thiskeyword.

还请记住,您可以将第二个参数传递给.forEach()指定要用作this关键字的对象的函数。

// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
  // element is the name of the key.
  // key is just a numerical value for the array
  // _array is the array of all the keys

  // this keyword = secondArg
  this.foo;
  this.bar();
}, secondArg);

回答by Andrew Foster aka Sheff

I'm new to node.js (about 2 weeks), but I've just created a module that recursively reports to the console the contents of an object. It will list all or search for a specific item and then drill down by a given depth if need be.

我是 node.js 的新手(大约 2 周),但我刚刚创建了一个模块,该模块递归地向控制台报告对象的内容。它将列出所有或搜索特定项目,然后在需要时按给定深度向下钻取。

Perhaps you can customize this to fit your needs. Keep It Simple! Why complicate?...

也许您可以自定义它以满足您的需求。把事情简单化!为什么复杂?...

'use strict';

//console.log("START: AFutils");

// Recusive console output report of an Object
// Use this as AFutils.reportObject(req, "", 1, 3); // To list all items in req object by 3 levels
// Use this as AFutils.reportObject(req, "headers", 1, 10); // To find "headers" item and then list by 10 levels
// yes, I'm OLD School!  I like to see the scope start AND end!!!  :-P
exports.reportObject = function(obj, key, level, deep) 
{
    if (!obj)
    { 
        return;
    }

    var nextLevel = level + 1;

    var keys, typer, prop;
    if(key != "")
    {   // requested field
        keys = key.split(']').join('').split('[');
    }
    else
    {   // do for all
        keys = Object.keys(obj);
    }
    var len = keys.length;
    var add = "";
    for(var j = 1; j < level; j++)
    {
        // I would normally do {add = add.substr(0, level)} of a precreated multi-tab [add] string here, but Sublime keeps replacing with spaces, even with the ["translate_tabs_to_spaces": false] setting!!! (angry)
        add += "\t";
    }

    for (var i = 0; i < len; i++) 
    {
        prop = obj[keys[i]];
        if(!prop)
        {
            // Don't show / waste of space in console window...
            //console.log(add + level + ": UNDEFINED [" + keys[i] + "]");
        }
        else
        {
            typer = typeof(prop);
            if(typer == "function")
            {
                // Don't bother showing fundtion code...
                console.log(add + level + ": [" + keys[i] + "] = {" + typer + "}");
            }
            else
            if(typer == "object")
            {
                console.log(add + level + ": [" + keys[i] + "] = {" + typer + "}");
                if(nextLevel <= deep)
                {
                    // drop the key search mechanism if first level item has been found...
                    this.reportObject(prop, "", nextLevel, deep); // Recurse into
                }
            }
            else
            {
                // Basic report
                console.log(add + level + ": [" + keys[i] + "] = {" + typer + "} = " + prop + ".");
            }
        }
    }
    return ;
};

//console.log("END: AFutils");

回答by H6.

For simple iteration of key/values, sometimes libraries like underscorejscan be your friend.

对于键/值的简单迭代,有时像underscorejs这样的库可能是你的朋友。

const _ = require('underscore');

_.each(a, function (value, key) {
    // handle
});

just for reference

仅供参考

回答by Lindy

adjust his code:

调整他的代码:

Object.prototype.each = function(iterateFunc) {
        var counter = 0,
keys = Object.keys(this),
currentKey,
len = keys.length;
        var that = this;
        var next = function() {

            if (counter < len) {
                currentKey = keys[counter++];
                iterateFunc(currentKey, that[currentKey]);

                next();
            } else {
                that = counter = keys = currentKey = len = next = undefined;
            }
        };
        next();
    };

    ({ property1: 'sdsfs', property2: 'chat' }).each(function(key, val) {
        // do things
        console.log(key);
    });