Lodash Get返回未定义的嵌套属性

时间:2018-08-13 23:56:53

标签: lodash

Lodash的get用于访问对象属性或返回默认值。但是,当我尝试将其与深层嵌套的属性一起使用时,它会返回undefined。

为什么get在这里返回undefined?我应该如何使用它来访问嵌套属性b

Lodash Get Docs

示例:

const foo = {a: {b: 1234}};
console.log(_.get(foo, ['a'])); // Returns { b: 1234 }
console.log(_.get(foo, ['a', 'b'])); // Returns undefined
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

或者:

const foo = { a: { b: 1234 } };
const bar = _.get(foo, 'a.b', 'it was undefined');
console.log(bar); // returns 'it was undefined'
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

0 个答案:

没有答案