[英]How to replace null values using orderBy in lodash
How can I properly replace null values with different values like a string using orderby
in lodash.如何在 lodash 中使用
orderby
将空值正确替换为不同的值,例如字符串。
Currently this is what I am doing to replace null values with a string.目前,这是我用字符串替换空值所做的工作。 I will use a separate
foreach loop
to replace the null values for .GroupDate
with a string and then use the orderBy
function.我将使用单独的
foreach loop
将.GroupDate
的空值替换为字符串,然后使用orderBy
函数。
test.forEach((e, i) => {
if (e.GroupDate === null) {
test[i].GroupDate = i.toString();
}
});
test = orderBy(test, [c => c.GroupDate, c => c.Index, c => c.Date], ['desc', 'asc']);
If there a better way to replace the foreach loop and add this condition inside the orderBy
?如果有更好的方法来替换 foreach 循环并将此条件添加到
orderBy
?
I tried this but it doesn't work:我试过这个,但它不起作用:
let groupDateNumber = 0;
test = orderBy(test, [
(c) => {
if (c.GroupDate === null) {
c.GroupDate = groupDateNumber.toString();
}
groupDateNumber++;
return c.GroupDate, c => c.Index, c => c.Timestamp;
}
], ['desc', 'asc']);
Your iteratee function is returning an array is that correct?你的 iteratee 函数正在返回一个数组是正确的吗? I believe what you want is
我相信你想要的是
let groupDateNumber = 0;
test = orderBy(test, [
(c) => {
if (c.GroupDate === null) {
c.GroupDate = groupDateNumber.toString();
}
groupDateNumber++;
return c.GroupDate;
},
c => c.Index,
c => c.Timestamp
], ['desc', 'asc']);
Another way you could do this through use of lodash seq method _(value)
and map
and orderBy
.另一种方法是通过使用 lodash seq 方法
_(value)
以及map
和orderBy
来做到这一点。 This should use lazy evaluation so it should be efficient, although I'm not sure how well chaining works with orderBy and sortBy.这应该使用惰性求值,所以它应该是有效的,尽管我不确定链接与 orderBy 和 sortBy 的效果如何。
test = _(test)
.map((e, i) => {
if (e.GroupDate === null) {
e.GroupDate = i.toString();
}
return e;
})
.orderBy([c => c.GroupDate, c => c.Index, c => c.Date], ['desc', 'asc'])
.value()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.