所以我们的代码中到处都是这种废话,我觉得 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}`);
即使帐户设置为文字,我仍然为上面的 profileId
得到 undefined
。这很奇怪……?
最终解决方案 (在 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}`);
})();
最佳答案
Lodash 的 _.get()
非常好,如果你想获取嵌套在对象 profile.player.id
中的东西,例如,它还有一个默认值如果未找到任何内容或出现错误,如本示例 _.get(account, 'profileId', null);
。
如果是对象的直接属性,可以使用destructuring with a default :
const account = {};
const game = { player: 'Sam' }
const { profileId = null } = account || {};
const { player } = game || {};
console.log(profileId);
console.log(player);
在 vanilla JS 中你可以使用 optional chaining (?.
) :
const obj = {
foo: {
bar: {
baz: 42,
},
},
};
const baz = obj?.foo?.bar?.baz; // 42
const safe = obj?.qux?.baz; // undefined
关于javascript - 比使用 Lodash 更好的获取属性(property)的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023211/