Kiksy
Kiksy

Reputation: 1292

Looping over objects in array and adding property to each

I'm getting an array of files, and then I want to add the date and size properties to each of those file objects, but using the code below, they don't get added. I know that's my fs.statSync(p + file).mtime.getTime() and fs.statSync(p + file).size have values in them.

var files = fs.readdirSync(p);

files.sort(function(a, b) {
           return fs.statSync(p + a).mtime.getTime() - 
                  fs.statSync(p + b).mtime.getTime();
});

files.forEach(function(file) {
    file.date = fs.statSync(p + file).mtime.getTime();
    file.size = fs.statSync(p + file).size;
});

console.log('files::'+files); // doesn' have the new file.date and file.size property.

Upvotes: 0

Views: 75

Answers (3)

Andy
Andy

Reputation: 63524

Similar to Eugene's answer, but this uses map:

files = files.map(function(file) {
  file.date = fs.statSync(p + file).mtime.getTime();
  file.size = fs.statSync(p + file).size;
  return file;
});

DEMO

Upvotes: 0

mike
mike

Reputation: 5213

The file variable is a local variable. Without having to create a new array as Eugene did, you can update the original array in this way:

var files = fs.readdirSync(p);

files.sort(function(a, b) {
           return fs.statSync(p + a).mtime.getTime() - 
                  fs.statSync(p + b).mtime.getTime();
});

files.forEach(function(file, index, array) {
    array[index].date = fs.statSync(p + file).mtime.getTime();
    array[index].size = fs.statSync(p + file).size;
});

console.log('files::'+files);

Upvotes: 0

Eugene Obrezkov
Eugene Obrezkov

Reputation: 2986

When you writing value into file variable it's not saving because file it's variable that lives into local scope. So a quick solution for this:

var files = fs.readdirSync(p),
    result = [];

files.sort(function(a, b) {
           return fs.statSync(p + a).mtime.getTime() - 
                  fs.statSync(p + b).mtime.getTime();
});

files.forEach(function(file) {
    file.date = fs.statSync(p + file).mtime.getTime();
    file.size = fs.statSync(p + file).size;
    result.push(file);
});

console.log('files::' + result);

Upvotes: 3

Related Questions