-1

If I have an object in JS like the example below:

var files = [
  {
    "name":"test.png",
    "type":"image/png",
    "size":3536
  },
  {
    "name":"test.png",
    "type":"image/png",
    "size":3536
  },
  {
    "name":"test.png",
    "type":"image/png",
    "size":3536
  }
];

What is the most efficient way to list the name of each object?

klinore
  • 2,589
  • 4
  • 19
  • 21
  • Some libs provide a `pluck(files, "name")` functionality for this – Bergi Jun 11 '14 at 21:44
  • function pluck(x) { return x[this]; }; var names = files.map(pluck, "name"), types=files.map(pluck, "type"); – dandavis Jun 11 '14 at 21:45
  • Or http://stackoverflow.com/q/20067386/218196, or any of these http://stackoverflow.com/search?q=%5Bjavascript%5D+access+object+property+array . Feel free to reopen and close with a more appropriate duplicate. – Felix Kling Jun 11 '14 at 21:46

4 Answers4

2

With a for loop:

for (var i = 0; i < files.length; i++) {
    console.log(files[i].name);
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

Probably not the most efficient, but the shortest and most readable (IMO):

var names = files.map(function (file) { return file.name; });

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

jgillich
  • 71,459
  • 6
  • 57
  • 85
0
for(var i=0,l=files.length;i<l;i++) {
    console.log(files[i].name);
}
lucuma
  • 18,247
  • 4
  • 66
  • 91
  • Why the unnecessary extra variable? – Etheryte Jun 11 '14 at 21:41
  • http://stackoverflow.com/questions/5349425/whats-the-fastest-way-to-loop-through-an-array-in-javascript – lucuma Jun 11 '14 at 21:42
  • If you actually look at the test data provided in the very question you linked to you can see that in modern browsers this isn't the fastest solution. Even so, this is another example of premature optimization. – Etheryte Jun 11 '14 at 21:44
  • The cached length on chrome v36 seems to be contradictory to your comment. https://blogs.oracle.com/greimer/resource/loop-test.html – lucuma Jun 11 '14 at 21:49
  • Read the jsperf linked in the same question you linked. There's a substantial amount of different samples from different systems (as opposed to your single test) and practically all show that the `while` solution is the fastest. – Etheryte Jun 11 '14 at 21:51
0

A simple for-loop should work best:

for (var i = 0; i < files.length; i++) {
    console.log(files[i].name);
}

To do the above as a key-value, you would create an object instead of an array:

var files = {
    "test1.png":
    {
        "type":"image/png",
        "size":3536
    },
    "test2.png":
    {
        "type":"image/png",
        "size":3536
    },
    "test3.png":
    {
        "type":"image/png",
        "size":3536
    }
};

Then you would iterate through them like this:

for (var key in files) {
    console.log("File name: " + key);
    console.log("File data: " + files[key]);
}
gregnr
  • 1,222
  • 8
  • 11