Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
152
rated 0 times [  159] [ 7]  / answers: 1 / hits: 8480  / 11 Years ago, thu, december 19, 2013, 12:00:00

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! :-)


More From » arrays

 Answers
3

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

[#49373] Wednesday, December 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keric

Total Points: 572
Total Questions: 93
Total Answers: 97

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;