比使用 Lodash 更好的获取属性的方法

Pos*_*Guy 6 javascript lodash reactjs

所以我们的代码中到处都是这些废话,IMO 太多 lodash。例如:

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

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

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

const profileId = _.get(account, 'profileId', null);
Run Code Online (Sandbox Code Playgroud)

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

const profileId = (account && account.profileId) || null
Run Code Online (Sandbox Code Playgroud)

还有其他想法吗?

更新

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

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

即使 account 设置为文字,我仍然得到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 unecessary 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}`);
})();
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 8

例如,_.get()如果你想在一个对象中嵌套一些东西,Lodash是非常好的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);
Run Code Online (Sandbox Code Playgroud)

一个更好的解决方案可能是 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
Run Code Online (Sandbox Code Playgroud)