0

In C# if I had a list for example of 3 ints [1,2,3], I could trasform that list into another with .Select in following way [1,2,3].Select(e => new { Id = e, Name = $"name:{e}"), which would return new array with 3 objects.

how can I get the same result in js without using for loop?

Jakub Kozera
  • 3,141
  • 1
  • 13
  • 23
  • 3
    Does this answer your question? [Javascript Equivalent to C# LINQ Select](https://stackoverflow.com/questions/18936774/javascript-equivalent-to-c-sharp-linq-select) – devNull May 11 '20 at 18:24

2 Answers2

4

You can use the map function like this:

var array = [1,2,3]

var result = array.map(e => ({id: e, name: `name:${e}`}))
console.log(result)

It returns the following result:

[ { id: 1, name: 'name:1' }, 
  { id: 2, name: 'name:2' }, 
  { id: 3, name: 'name:3' } ]

Here is the map function docs:

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

Jakub Kozera
  • 3,141
  • 1
  • 13
  • 23
0

Yes, it is called map(example with integers, but you can map into objects too):

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
Guru Stron
  • 102,774
  • 10
  • 95
  • 132