我一直在用这个拔头发 - 我有以下数组,继续一个对象 - 它包含一个凭证数组(包含可能无限数量的对象)
var retailer = [ { _id: 52000c,
address: 'bla bla bla',
email: 'test@emailaddress',
img: 'http://bla.jpg',
intro: ' hello',
strapLine: 'goodbye',
tel: '0000 0000000',
title: 'YE OLDE SHOPPE',
website: 'http://',
vouchers:
[ { _id: 523d003,
barcode: false,
description: 'blah',
endTime: '20 December 2013',
hidden: true,
redemptionCode: 'redemptionCode',
smallPrint: 'blah.',
startTime: 'Today',
title: 'blahbla' },
{ _id: 523de3,
barcode: false,
description: 'blah',
endTime: '20 December 2013',
hidden: true,
redemptionCode: 'redemptionCode',
smallPrint: 'blah.',
startTime: 'Today',
title: 'blahbla' },
{ _id: 523dr,
barcode: false,
description: 'blah',
endTime: '20 December 2013',
hidden: false,
redemptionCode: 'redemptionCode',
smallPrint: 'blah.',
startTime: 'Today',
title: 'blahbla' } ]
} ]
使用下划线.js,我正在尝试过滤掉那些属性为 hidden (hidden == true) 的凭证对象 - 所以我最终得到以下内容,这样我最终只会得到那些可见的凭证(隐藏 == false)
var retailer = [ { _id: 52000c,
address: 'bla bla bla',
email: 'test@emailaddress',
img: 'http://bla.jpg',
intro: ' hello',
strapLine: 'goodbye',
tel: '0000 0000000',
title: 'YE OLDE SHOPPE',
website: 'http://',
vouchers:
[{ _id: 523dr,
barcode: false,
description: 'blah',
endTime: '20 December 2013',
hidden: false,
redemptionCode: 'redemptionCode',
smallPrint: 'blah.',
startTime: 'Today',
title: 'blahbla' }]
} ]
所以使用下划线 js,我根据之前的堆栈溢出线程编写了以下内容(带下划线的过滤数组.js)
var visibleVouchers = _(retailer[0].vouchers).filter(function (x) { return !x.hidden;});
这将返回所有可见的代金券 - 但是,我在此过程中失去了零售商。最好的方法是什么?我已经尝试了很多不同的东西 - 即,试图用新的替换旧的voucheers阵列 - 但它似乎不起作用。
谢谢抢
在零售商上使用_.map()
,这是一对一的映射。在回调(每个零售商项目)中,使用 _.filter()
(或_.reject()
,根据您的感觉)过滤掉凭证。
var arrRetailers = _.map(retailers, function(retailer) {
var item = _.extend({}, retailer);
item.vouchers = _.filter(retailer.vouchers, function(voucher) {
return !voucher.hidden;
}) || []; //in case of there is no "visible" voucher
return item;
});
这将返回一个新数组,并且不会更改初始零售商数组。
如果您更喜欢_.reject()
,则必须相应地调整您的回调:
_.reject(retailer.vouchers, function(voucher) {
return voucher.hidden; //note there is no exclamation mark
}) || [];
希望这有帮助!
我找到了一篇博客文章 http://www.untitleddesigns.com/2011/javascript-replace-array-contents/似乎回答了我的问题 - 它确实有效,尽管我不熟悉原型 - 所以不太清楚它为什么有效。
var visibleVouchers = _(retailer[0].vouchers).filter(function (x) { return !x.hidden;});
retailer[0].vouchers.length = 0;
Array.prototype.push.apply(retailer[0].vouchers, visibleVouchers);