我正在尝试使用lodash链同步执行操作,但似乎首先执行.tap(),我无法找到使用promise这样做的正确方法。我虽然lodash中的链允许操作以同步方式跟随,但意味着点击将不会执行,直到forEach结束
const ids = [
{
"id": 1,
"refs": [
{
"skuId": 693194,
"sizeId": "12M",
"colorId": "ROSE"
},
{
"skuId": 693195,
"sizeId": "14M",
"colorId": "ROSE"
},
{
"skuId": 973804,
"sizeId": "6M",
"colorId": "GREEN"
}
]
},
{
"id": 2,
"refs": [
{
"skuId": 693174,
"sizeId": "13M",
"colorId": "RED"
},
{
"skuId": 693995,
"sizeId": "14M",
"colorId": "BLUS"
}
]
}
]
let id = 1
_(ids)
.chain()
.map(value => {
id = _.result(_.find(value.refs, function(sku) {
return sku.colorId === 'ROSE' &&
sku.sizeId === '14M';
}), 'skuId');
})
.tap(() => console.log('id: ', id))
.value()
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
答案 0 :(得分:0)
我认为您没有正确使用chain
- check out the docs,您必须通过调用.value()
来解包该值,就像在文档示例中一样。 Tap实际上并未先执行。
let id = null;
_.chain(ids)
.forEach(value => {
id = _.result(_.find(value.refs, function(sku) {
return sku.colorId === 'ROSE'
&& sku.sizeId === '14M';
}), 'skuId');
})
.tap(() => console.log(id))
.value();
我不是100%确定你要做什么,但我会重写它以使用map来摆脱那个外在的id:
const ids = [
{
"id": 1,
"refs": [
{
"skuId": 693194,
"sizeId": "12M",
"colorId": "ROSE"
},
{
"skuId": 693195,
"sizeId": "14M",
"colorId": "ROSE"
},
{
"skuId": 973804,
"sizeId": "6M",
"colorId": "GREEN"
}
]
},
{
"id": 2,
"refs": [
{
"skuId": 693174,
"sizeId": "13M",
"colorId": "RED"
},
{
"skuId": 693995,
"sizeId": "14M",
"colorId": "BLUS"
}
]
}
]
let val = _.chain(ids)
.map(value => {
return _.result(
_.find(
value.refs,
sku => sku.colorId === 'ROSE' && sku.sizeId === '14M'
),
'skuId');
})
.value();
console.log(val);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
您仍然可能需要稍微调整一下代码以获得您期望的结果。
答案 1 :(得分:0)
如果您在id
内添加一行以转储map
的值,您会注意到id
被设置了两次而第二次被null
覆盖了你想要的价值。
const ids = [
{
"id": 1,
"refs": [
{
"skuId": 693194,
"sizeId": "12M",
"colorId": "ROSE"
},
{
"skuId": 693195,
"sizeId": "14M",
"colorId": "ROSE"
},
{
"skuId": 973804,
"sizeId": "6M",
"colorId": "GREEN"
}
]
},
{
"id": 2,
"refs": [
{
"skuId": 693174,
"sizeId": "13M",
"colorId": "RED"
},
{
"skuId": 693995,
"sizeId": "14M",
"colorId": "BLUS"
}
]
}
]
let id = 1
_(ids)
.chain()
.map(value => {
id = _.result(_.find(value.refs, function(sku) {
return sku.colorId === 'ROSE' &&
sku.sizeId === '14M';
}), 'skuId');
// Add this line to inspect the id value in map
console.log('id (in map): ', id);
})
.tap(() => console.log('id: ', id))
.value()
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>