programing

C# LINQ에 해당하는 Javascript 선택

cafebook 2023. 8. 16. 22:36
반응형

C# LINQ에 해당하는 Javascript 선택

이 질문에 따라 다음을 수행합니다.

확인란 목록과 함께 선택한 바인딩을 녹아웃에서 사용하면 모든 확인란이 선택됩니다.

배열에서 선택할 수 있는 확인란을 몇 개 만들었습니다.위의 게시물에서 가져온 작업용 바이올린:

http://jsfiddle.net/NsCXJ/

과일의 ID 배열만 만드는 간단한 방법이 있습니까?

저는 C#과 함께 집에 더 있고, 거기서 저는 다음과 같은 것을 할 수 있습니다.selectedFruits.select(fruit=>fruit.id);

javascript/jquery와 비슷한 것을 할 수 있는 method/readymade 기능이 있습니까?아니면 가장 간단한 옵션은 목록을 반복하여 두 번째 배열을 만드는 것입니까?저는 JSON의 서버에 어레이를 다시 게시할 예정이므로 전송되는 데이터를 최소화하기 위해 노력하고 있습니다.

예, Array.map() 또는 $.map()은 동일한 작업을 수행합니다.

//array.map:
var ids = this.fruits.map(function(v){
    return v.Id;
});

//jQuery.map:
var ids2 = $.map(this.fruits, function (v){
    return v.Id;
});

console.log(ids, ids2);

http://jsfiddle.net/NsCXJ/1/

array.map은 이전 브라우저에서 지원되지 않으므로 jQuery 방법을 사용하는 것이 좋습니다.

어떤 이유로 다른 하나를 선호하는 경우 이전 브라우저 지원을 위해 항상 폴리필을 추가할 수 있습니다.

언제든지 어레이 프로토타입에 사용자 지정 메서드를 추가할 수 있습니다.

Array.prototype.select = function(expr){
    var arr = this;
    //do custom stuff
    return arr.map(expr); //or $.map(expr);
};

var ids = this.fruits.select(function(v){
    return v.Id;
});

문자열을 전달하는 경우 함수 생성자를 사용하는 확장 버전입니다.아마도 가지고 놀만한 것:

Array.prototype.select = function(expr){
    var arr = this;

    switch(typeof expr){

        case 'function':
            return $.map(arr, expr);
            break;

        case 'string':

            try{

                var func = new Function(expr.split('.')[0], 
                                       'return ' + expr + ';');
                return $.map(arr, func);

            }catch(e){

                return null;
            }

            break;

        default:
            throw new ReferenceError('expr not defined or not supported');
            break;
    }

};

console.log(fruits.select('x.Id'));

http://jsfiddle.net/aL85j/

업데이트:

이것이 매우 인기 있는 답변이 되었기 때문에, 저는 비슷한 나의 의견을 추가합니다.where()+firstOrDefault()이것들은 문자열 기반 함수 생성자 접근법(가장 빠른 것)에도 사용될 수 있지만, 여기 객체 리터럴을 필터로 사용하는 다른 접근법이 있습니다.

Array.prototype.where = function (filter) {

    var collection = this;

    switch(typeof filter) { 

        case 'function': 
            return $.grep(collection, filter); 

        case 'object':
            for(var property in filter) {
              if(!filter.hasOwnProperty(property)) 
                  continue; // ignore inherited properties

              collection = $.grep(collection, function (item) {
                  return item[property] === filter[property];
              });
            }
            return collection.slice(0); // copy the array 
                                      // (in case of empty object filter)

        default: 
            throw new TypeError('func must be either a' +
                'function or an object of properties and values to filter by'); 
    }
};


Array.prototype.firstOrDefault = function(func){
    return this.where(func)[0] || null;
};

용도:

var persons = [{ name: 'foo', age: 1 }, { name: 'bar', age: 2 }];

// returns an array with one element:
var result1 = persons.where({ age: 1, name: 'foo' });

// returns the first matching item in the array, or null if no match
var result2 = persons.firstOrDefault({ age: 1, name: 'foo' }); 

다음은 함수 생성자와 객체 리터럴 속도를 비교하기 위한 jsperf 테스트입니다.전자를 사용하려면 문자열을 올바르게 따옴표로 묶어야 합니다.

제 개인적인 선호는 1-2 속성을 필터링할 때 객체 리터럴 기반 솔루션을 사용하고, 더 복잡한 필터링을 위해 콜백 함수를 전달하는 것입니다.

네이티브 객체 프로토타입에 메서드를 추가할 때의 일반적인 팁 두 가지로 이 작업을 마치겠습니다.

  1. 덮어쓰기 전에 기존 메서드가 있는지 확인합니다. 예:

    if(!Array.prototype.where) { Array.prototype.where = ...

  2. IE8 이하를 지원할 필요가 없는 경우 Object.defineProperty를 사용하여 메서드를 정의하여 열거할 수 없도록 합니다.누군가 사용한 경우for..in배열에서(처음에는 잘못되었지만) 열거형 속성도 반복합니다.미리 알려주세요.

답장이 늦었다는 것은 알지만, 저에게 유용했습니다!완료하기 위해, 사용하기$.grep당신이 linq를 에뮬레이트할 수 있는 함수where().

링크:

var maleNames = people
.Where(p => p.Sex == "M")
.Select(p => p.Name)

Javascript:

// replace where  with $.grep
//         select with $.map
var maleNames = $.grep(people, function (p) { return p.Sex == 'M'; })
            .map(function (p) { return p.Name; });

ES6 방식:

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);
}

https://jsfiddle.net/52dpucey/ 에서도 확인할 수 있습니다.

녹아웃을 사용하고 있으므로 녹아웃 유틸리티 기능을 사용하는 것을 고려해야 합니다.arrayMap()이것은 다른 어레이 유틸리티 기능입니다.

다음은 어레이 유틸리티 함수와 이와 동등한 LINQ 방법의 목록입니다.

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)

예를 들어 다음과 같은 작업을 수행할 수 있습니다.

var mapped = ko.utils.arrayMap(selectedFruits, function (fruit) {
    return fruit.id;
});

javascript에서 LINQ와 같은 인터페이스를 사용하려면 많은 LINQ 메서드에 대한 멋진 인터페이스를 제공하는 linq.js와 같은 라이브러리를 사용할 수 있습니다.

var mapped = Enumerable.from(selectedFruits)
    .select("$.id") // shorthand for `x => x.id`
    .toArray();

시도해 볼 수도 있습니다.

당신의

selectedFruits.select(fruit=>fruit.id);

될 것이다

Enumerable.From(selectedFruits).Select(function (fruit) { return fruit.id;  });

가장 유사한 C#Select아날로그는 a일 것입니다.map기능.그냥 사용:

var ids = selectedFruits.map(fruit => fruit.id);

에서 모든 ID를 선택합니다.selectedFruits배열

외부 의존성이 필요하지 않고 순수한 자바스크립트만 필요합니다.찾을 수 있습니다.map여기 설명서: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

저는 TsLinq.codeplex.com 아래에 타입스크립트용 Linq 라이브러리를 구축하여 일반 자바스크립트에도 사용할 수 있습니다.이 라이브러리는 Linq.js보다 2-3배 빠르며 모든 Linq 방법에 대한 단위 검정을 포함합니다.아마 당신은 그것을 검토할 수 있을 것입니다.

많은 linq like 함수를 제공하는 언더스코어.js를 살펴보세요.당신이 제시한 예에서는 지도 기능을 사용할 것입니다.

언급URL : https://stackoverflow.com/questions/18936774/javascript-equivalent-to-c-sharp-linq-select

반응형