NodeJS Difference Object.keys (array) .length and array.length

I have a function that reads files from a file system and stores them in an array. Subsequently, I want to add a key / value pair to this element. However, the forEach loop is not executed, because apparently there is no element in it.

readFilesFromDirectory(folder, elements, 'json', function(){
    log(Object.keys(elements).length,0);
    log(elements.length,0);
    elements.forEach(function(elem){
        elem["newKey"] = 1;
    });
});

My log contains the following lines:

1
0

The first length method works, the second does not. I would like to know what I am doing wrong for the second function and how I can fix it.

In fact, my main goal is to add a new key. However, I don’t know how to use some Object.keyValues ​​(elements) .forEach (function (elem) {...} objects in my code. If you have a hint of this, that would be fine too.

I am very grateful for your understanding !:-)

+4
1

Object.keys() , for...in ( , for-in , ).

Object.keys , , , . , .

var arr = ["a", "b", "c"];
alert(Object.keys(arr)); // will alert "0,1,2"

// array like object
var obj = { 0 : "a", 1 : "b", 2 : "c"};
alert(Object.keys(obj)); // will alert "0,1,2"

// array like object with random key ordering
var an_obj = { 100: "a", 2: "b", 7: "c"};
alert(Object.keys(an_obj)); // will alert "2, 7, 100"

// getFoo is property which isn't enumerable
var my_obj = Object.create({}, { getFoo : { value : function () { return this.foo } }});
my_obj.foo = 1;

alert(Object.keys(my_obj)); // will alert only foo
+4

All Articles