Iteracja nad kluczami obiektów w węźle.js
Od wersji Javascript 1.7 istnieje obiekt Iterator , który pozwala na to:
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();
Jest coś takiego w node.js ?
Teraz używam:
function Iterator(o){
/*var k=[];
for(var i in o){
k.push(i);
}*/
var k=Object.keys(o);
return {
next:function(){
return k.shift();
}
};
}
Ale to generuje dużo narzutu, przechowując wszystkie klucze obiektu w k
.
4 answers
To, co chcesz, to leniwa iteracja nad obiektem lub tablicą. Nie jest to możliwe w ES5 (więc nie jest to możliwe w node.js). W końcu to dostaniemy.
Jedynym rozwiązaniem jest znalezienie modułu węzła, który rozszerza V8 o implementację iteratorów (i prawdopodobnie generatorów). Nie mogłem znaleźć żadnej realizacji. Możesz spojrzeć na kod źródłowy spidermonkey i spróbować napisać go w C++ jako rozszerzenie V8.
Można spróbować następujące, jednak będzie również załadować wszystkie klucze do pamięć
Object.keys(o).forEach(function(key) {
var val = o[key];
logic();
});
Jednak ponieważ Object.keys
jest metodą natywną, może to pozwolić na lepszą optymalizację.
Jak widać obiekt.klawisze są znacznie szybsze. To, czy rzeczywiste przechowywanie pamięci jest bardziej optymalne, to inna sprawa.
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);
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-17 15:34:21
Pamiętaj również, że możesz przekazać drugi argument do .forEach()
Funkcja określająca obiekt do użycia jako słowo kluczowe 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);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-22 03:08:49
Jestem nowy w node.js (około 2 tygodni), ale właśnie stworzyłem moduł, który rekurencyjnie raportuje do konsoli zawartość obiektu. Wyświetli wszystkie lub wyszukuje konkretny przedmiot, a następnie w razie potrzeby wywierci w dół o określoną głębokość.
Być może możesz dostosować to do swoich potrzeb. To Proste! Po co komplikować?...
'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");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-11 11:41:11
Dopasuj jego kod:
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);
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-26 08:54:46