比使用 Lodash 更好的获取财产的方法

新手上路,请多包涵

所以我们的代码中到处都是这种废话,我觉得 lodash 太多了。例如:

 const profileId = _.get(account, 'profileId', null);
const player = _.get(someCustomObject, 'player'); // Why??????  why not just someCustomObject.player?

当您只能通过对象访问对象属性时,对所有内容都使用 lodash 是我还是荒谬!总的来说,我们使用 lodash,它在很多地方都有些矫枉过正,使代码更加冗长和难以阅读。

在这种情况下,我们也不需要 lodash:

 const profileId = _.get(account, 'profileId', null);

如果没有 lodash,有什么方法可以做到这一点?那是我的问题。以下是一些想法:

 const profileId = (account && account.profileId) || null

还有其他想法吗?

更新

有趣的是,与 Ori 的回答一致,但这里只是一个观察。我想删除默认 profileId 为 null 只是因为我觉得这是不必要的。但是为什么这个 profileId 没有设置到帐户对象?

 const account = {};
const game = { player: 'Sam' }

console.log(`account: ${account}`);

const { profileId } = account || {};
const { player } = game || {};

console.log(`profileId: ${profileId} // why is this undefined if account has value {}???`);
console.log(`player: ${player}`);

即使帐户设置为文字,我仍然得到 undefined profileId 。这很奇怪..?

_最终解决方案_(在 codepen.io 中运行它,因为你需要加载 lodash)

 console.log(" Example Clean Code without Lodash")
console.log('===============================')

let account = {};
const game = { player: 'Sam' }

console.log(`account: ${account}`);

const { profileId = null } = account;
const { player } = game || {};

console.log(`profileId: ${profileId}`);
console.log(`player: ${player}`);

/* using IIFE so profileId doesn't conflict with example above */
(() => {
  console.log("Example using unnecessary Lodash")
  console.log('===============================')

  let profileId = _.get(account, 'profileId', null);
  const game = { player: 'Sam' }

  console.log(`account2: ${account}`);

  const { player } = game || {};

  console.log(`profileId: ${profileId}`);
  console.log(`player: ${player}`);
})();

原文由 PositiveGuy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 420
2 个回答

Lodash 的 _.get() 如果你想在一个对象中嵌套一些东西真的很好 profile.player.id 如果没有找到任何东西或有错误,它也有一个默认值,就像这个例子一样 _.get(account, 'profileId', null);

如果它是对象的直接属性,则可以使用 默认的解构

 const account = {};
const game = { player: 'Sam' }

const { profileId = null } = account || {};
const { player } = game || {};

console.log(profileId);
console.log(player);

一个更好的解决方案可能是 stage-1 proposal-optional-chaining 如果它进入规范,尽管你现在可以将它与 babel 插件一起使用:

 const obj = {
  foo: {
    bar: {
      baz: 42,
    },
  },
};

const baz = obj?.foo?.bar?.baz; // 42

const safe = obj?.qux?.baz; // undefined

原文由 Ori Drori 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是文章“ 在 JavaScript 中安全访问深度嵌套的值”中的一个很好的单行代码

export function _get(object, path, defval = null) {
    if (typeof path === "string") path = path.split(".");
    return path.reduce((xs, x) => (xs && xs[x] ? xs[x] : defval), object);
}

您还可以使用这个很棒的零依赖实用程序库 https://github.com/angus-c/just

原文由 xpuu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题