我只是在寻找基于lodash的解决方案。我无法使用javascript 6功能。
以下代码有效。它在circleStoreId数组中找到包含请求的字符串的“记录”。我觉得应该有一个更简单,更实用的方法来实现这一目标。我是否缺少更好的解决方案?
var RECORDS = [
{
circleStoreId: [
'AKWX3MWZ0FFT6', // WS Herb Counter
'C9VKT4W6GQNBM', // WS Bar
'KPN3W7SHAH1P6' // WS Front Counter
],
acmeLocationIId: 3,
channelIId: 2
},
{
circleStoreId: [
'0ZK8FZHPD5G71', // SK Herb Counter
'6VCZ7NNAF2VWW' // SK Bar
],
acmeLocationIId: 4,
channelIId: 1
}
// Ready for the next retail location to be added...
];
var f = _.find(RECORDS, function(r) {
return _.indexOf(r.circleStoreId, '6VCZ7NNAF2VWW') > -1;
});
console.log(f)
控制台将输出
{circleStoreId:Array(2),acmeLocationIId:4,channelIId:1}
答案 0 :(得分:2)
也许使用includes
而不是indexOf
。但这并没有太大改善。
var f = _.find(RECORDS, function(r) {
return _.includes(r.circleStoreId, '6VCZ7NNAF2VWW'));
});
console.log(f)
答案 1 :(得分:1)
使用ES6 Array.prototype.find():
var RECORDS = [
{
circleStoreId: [
'AKWX3MWZ0FFT6', // WS Herb Counter
'C9VKT4W6GQNBM', // WS Bar
'KPN3W7SHAH1P6' // WS Front Counter
],
acmeLocationIId: 3,
channelIId: 2
},
{
circleStoreId: [
'0ZK8FZHPD5G71', // SK Herb Counter
'6VCZ7NNAF2VWW' // SK Bar
],
acmeLocationIId: 4,
channelIId: 1
}
// Ready for the next retail location to be added...
];
var f = RECORDS.find( r => r.circleStoreId.includes('6VCZ7NNAF2VWW'))
console.log(f)