简体   繁体   English

如何在 lodash 中使用 orderBy 替换空值

[英]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)以及maporderBy来做到这一点。 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()

You can use a function array as second parameter and check for null values:您可以使用函数数组作为第二个参数并检查空值:

const textIfNull = '';

test = orderBy(test, [c => c.GroupDate || textIfNull, c => c.Index, c => c.Date], ['desc', 'asc']);

I created a sandbox with an example for you.我为您创建了一个带有示例的沙箱

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM