Freddy Bonda
Freddy Bonda

Reputation: 1259

Fastest way to loop through an object array and get specific keys

Say I have this array:

Dogs = [
    {Name: 'Sparky', OwnerID: 1},
    {Name: 'Pooch', OwnerID: 2},
    {Name: 'Sneak', OwnerID: 1}
]

What is the fastest way for me to do this:

dogNames = Dogs.map(element => element.Name);

I was just wondering if there is something like this:

dogNames = Dogs[...Name];

Upvotes: 0

Views: 66

Answers (2)

Davi
Davi

Reputation: 4147

It depends on what you mean by saying "fastest". Do you mean execution time? Fastest to type? Easiest to understand?

When "fastest to type" and "easiest to understand" is what you mean, then I'd rather say something like array.map(x => x.prop) is probably the fastest. You might find a shorter way to type it besides removing the variable and property names, but I can't think of one.

In terms of execution time, most people believe that using loops is the fastest way:

let names = [];
for (let i = 0; i < dogs.length; i += 1) {
  names[i] = dogs[i].Name;
}

Personally, I avoid loops whenever possible and stick with map, filter, reduce – to be honest, mainly because for most projects my execution time is more expensive than the execution time of my script.

Anyway, deciding that is up to you.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386620

You could take a closure over the wanted key an map the result of only a single property.

const only = k => o => o[k];

var dogs = [{ Name: 'Sparky', OwnerID: 1 }, { Name: 'Pooch', OwnerID: 2 }, { Name: 'Sneak', OwnerID: 1 }],
    dogNames = dogs.map(only('Name'));
    
console.log(dogNames);

Upvotes: 1

Related Questions