Following this question here :
Using the checked binding in knockout with a list of checkboxes checks all the checkboxes
I\'ve c
The ES6 way:
let people = [{firstName:'Alice',lastName:'Cooper'},{firstName:'Bob',age:'Dylan'}];
let names = Array.from(people, p => p.firstName);
for (let name of names) {
console.log(name);
}
also at: https://jsfiddle.net/52dpucey/
I am answering the title of the question rather than the original question which was more specific.
With the new features of Javascript like iterators and generator functions and objects, something like LINQ for Javascript becomes possible. Note that linq.js, for example, uses a completely different approach, using regular expressions, probably to overcome the lack of support in the language at the time.
With that being said, I've written a LINQ library for Javascript and you can find it at https://github.com/Siderite/LInQer. Comments and discussion at https://siderite.dev/blog/linq-in-javascript-linqer.
From previous answers, only Manipula seems to be what one would expect from a LINQ port in Javascript.
Take a look at fluent, it supports almost everything LINQ does and based on iterables - so it works with maps, generator functions, arrays, everything iterable.
The most similar C# Select
analogue would be a map
function.
Just use:
var ids = selectedFruits.map(fruit => fruit.id);
to select all ids from selectedFruits
array.
It doesn't require any external dependencies, just pure JavaScript. You can find map
documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Take a peek at underscore.js which provides many linq like functions. In the example you give you would use the map function.
Since you're using knockout, you should consider using the knockout utility function arrayMap()
and it's other array utility functions.
Here's a listing of array utility functions and their equivalent LINQ methods:
arrayFilter() -> Where()
arrayFirst() -> First()
arrayForEach() -> (no direct equivalent)
arrayGetDistictValues() -> Distinct()
arrayIndexOf() -> IndexOf()
arrayMap() -> Select()
arrayPushAll() -> (no direct equivalent)
arrayRemoveItem() -> (no direct equivalent)
compareArrays() -> (no direct equivalent)
So what you could do in your example is this:
var mapped = ko.utils.arrayMap(selectedFruits, function (fruit) {
return fruit.id;
});
If you want a LINQ like interface in javascript, you could use a library such as linq.js which offers a nice interface to many of the LINQ methods.
var mapped = Enumerable.From(selectedFruits)
.Select("$.id") // 1 of 3 different ways to specify a selector function
.ToArray();