簡體   English   中英

如何使用 lodash 迭代對象值並用 null 替換未定義?

[英]How to iterate an Objects values and replace undefined with null using lodash?

我知道如何使用本機 Object.entries 和 reducer 函數來做到這一點。 但是有可能用 lodash 函數代替它嗎?

const object = {
  foo: 'bar',
  baz: undefined,
}

const nulledObject = Object.entries(object).reduce(
  (acc, [key, value]) => ({
    ...acc,
    [key]: typeof value === 'undefined' ? null : value,
  }),
  {}
);

// {
//   foo: 'bar',
//   baz: null,
// }

我的願望是這樣的:

_cloneWith(object, (value) => (typeof value === 'undefined' ? null : value));

我認為_.assignWith是你要找的:

const nulledObject = _.assignWith({}, object, 
    (_, value) => typeof value == 'undefined' ? null : value);

發布此問題后,我找到了另一個解決方案:

const nulledObject = _.mapValues(object, 
    (value) => (value === undefined ? null : value));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM