Jonathan Wood
Jonathan Wood

Reputation: 67283

Does JavaScript provide a way to build a new collection with just one property from another collection?

In C#, I can do the following:

class Item
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

Item[] Items = new[]
{
    new() { Name = "Bob", Email = "[email protected]", Phone = "555-5555" },
    new() { Name = "Carl", Email = "[email protected]", Phone = "555-5555" },
    new() { Name = "Ted", Email = "[email protected]", Phone = "555-5555" },
};

IEnumerable<string> names = Items.Select(i => i.Name);

The last line builds a collection of just the names from Items ("Bob", "Carl" and "Ted").

Is there a way to do the same thing in JavaScript without writing a loop and building the array yourself?

Upvotes: 1

Views: 58

Answers (1)

Deepak
Deepak

Reputation: 2742

There is a similar concept in JavaScript and it is called the map :)

let details = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Steve' },
  { id: 3, name: 'Mike' },
  { id: 4, name: 'Ericson' }
];

console.log(details.map(detail => { return detail.name }))

Upvotes: 3

Related Questions