下面是这个问题:

Using the checked binding in knockout with a list of checkboxes checks all the checkboxes

I've created some checkboxes using knockout that allow selection from an array. working fiddle taken from above post:

http://jsfiddle.net/NsCXJ/

有没有一种简单的方法来创建一个仅包含水果ID的数组?

我更熟悉C#,在那里我会做一些关于selectedFruits.select(fruit=>fruit.id);的事情

Is there some method/ready made function for doing something similar with javascript/jquery? Or would the simplest option be to loop through the list and create a second array? I intend to post the array back to the server in JSON so am trying to minimize the data sent.

推荐答案

Yes, Array.map() or $.map() does the same thing.

//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/

从数组开始.map在旧浏览器中不受支持,我建议您坚持使用jQuery方法.

If you prefer the other one for some reason you could always add a polyfill for old browser support.

You can always add custom methods to the array prototype as well:

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

An extended version that uses the function constructor if you pass a string. Something to play around with perhaps:

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/

Update:

既然这已经成为一个很受欢迎的答案,我添加了类似的我的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;
};

Usage:

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

Here is a jsperf test to compare the function constructor vs object literal speed. If you decide to use the former, keep in mind to quote strings correctly.

My personal preference is to use the object literal based solutions when filtering 1-2 properties, and pass a callback function for more complex filtering.

在将方法添加到本机对象原型时,我将用两个一般提示来结束本文:

  1. 在覆盖之前判断现有方法的出现情况,例如:

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

  2. 如果不需要支持IE8及以下版本,请使用Object.defineProperty定义方法,使其不可枚举.如果有人在数组上使用for..in(这首先是错误的)

Jquery相关问答推荐

我在自定义 WordPress 插件中使用 ajax 时收到错误请求

是否可以从不可见的 DataTables 列访问数据?

DataTables - this.api 用于回调函数中的多个表

如何使用 jQuery 的 drop 事件上传从桌面拖动的文件?

Bootstrap 3 RC 1 中的 typeahead JavaScript 模块在哪里?

在 `click` 和 `enter` 上触发事件

如何使用 jQuery 重置 jquery Select 的 Select 选项?

如何在 Slick 轮播项目之间添加空格

如何使用jQuery找到元素顶部的垂直距离(以px为单位)

删除所有子元素的 CLASS

如何在 JQuery UI 自动完成中使用 source:function()... 和 AJAX

将参数附加到 URL 而不刷新

在 HTML 表单提交上制作 Enter 键而不是激活按钮

jQuery ajax 在 asp.net mvc 中上传文件

使用带有 HTML 表格的 jQuery UI 可排序

消除移动 Safari 中点击事件的 300 毫秒延迟

jQuery vs jQuery Mobile vs jQuery UI?

使用 jQuery 获取鼠标单击图像的 X/Y 坐标

在事件中使用 jQuery 获取被点击的元素?

jQuery - 从元素内部 Select 元素