4

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

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 is working, the second is not. I would like to know what I am doing wrong for the second function and how I can fix it.

Actually, my main objective is to add the new key. However, I do not know how to use some Object.keyValues(elements).forEach(function(elem){...} in my code. If you have a hint for that, this would also be nice.

I would really appreciate some insight here! :-)

1 Answer 1

4

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Object.keys returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

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
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! I totally forgot about the for...in loop - using this now and adding the new key/value pair.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.