所以我们的代码中到处都是这种废话,我觉得 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 许可协议
Lodash 的
_.get()
如果你想在一个对象中嵌套一些东西真的很好profile.player.id
如果没有找到任何东西或有错误,它也有一个默认值,就像这个例子一样_.get(account, 'profileId', null);
。如果它是对象的直接属性,则可以使用 默认的解构:
一个更好的解决方案可能是 stage-1 proposal-optional-chaining 如果它进入规范,尽管你现在可以将它与 babel 插件一起使用: