ใช่Array.map ()หรือ$ .map ()ทำสิ่งเดียวกัน
var ids = this.fruits.map(function(v){
return v.Id;
});
var ids2 = $.map(this.fruits, function (v){
return v.Id;
});
console.log(ids, ids2);
http://jsfiddle.net/NsCXJ/1/
เนื่องจากไม่รองรับ array.map ในเบราว์เซอร์รุ่นเก่าฉันขอแนะนำให้คุณใช้วิธี jQuery
หากคุณต้องการตัวเลือกอื่นด้วยเหตุผลบางประการคุณสามารถเพิ่ม polyfill เพื่อรองรับเบราว์เซอร์รุ่นเก่าได้ตลอดเวลา
คุณสามารถเพิ่มวิธีการที่กำหนดเองลงในต้นแบบอาร์เรย์ได้ตลอดเวลา:
Array.prototype.select = function(expr){
var arr = this;
return arr.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;
collection = $.grep(collection, function (item) {
return item[property] === filter[property];
});
}
return collection.slice(0);
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 }];
var result1 = persons.where({ age: 1, name: 'foo' });
var result2 = persons.firstOrDefault({ age: 1, name: 'foo' });
นี่คือการทดสอบ jsperfเพื่อเปรียบเทียบตัวสร้างฟังก์ชันเทียบกับความเร็วตามตัวอักษรของวัตถุ หากคุณตัดสินใจที่จะใช้แบบเดิมโปรดจำไว้ว่าต้องอ้างอิงสตริงอย่างถูกต้อง
ความชอบส่วนตัวของฉันคือการใช้โซลูชันตามตัวอักษรของออบเจ็กต์เมื่อกรองคุณสมบัติ 1-2 และส่งผ่านฟังก์ชันเรียกกลับเพื่อการกรองที่ซับซ้อนยิ่งขึ้น
ฉันจะจบลงด้วยเคล็ดลับทั่วไป 2 ข้อเมื่อเพิ่มวิธีการให้กับต้นแบบวัตถุดั้งเดิม:
ตรวจสอบการเกิดขึ้นของวิธีการที่มีอยู่ก่อนที่จะเขียนทับเช่น:
if(!Array.prototype.where) {
Array.prototype.where = ...
หากคุณไม่ต้องการรองรับ IE8 หรือต่ำกว่าให้กำหนดวิธีการโดยใช้Object.definePropertyเพื่อให้ไม่สามารถนับได้ หากมีคนใช้for..in
อาร์เรย์ (ซึ่งผิดตั้งแต่แรก) พวกเขาจะทำซ้ำคุณสมบัติที่แจกแจงได้เช่นกัน เพียงแค่หัวขึ้น