Lodash的get
用于访问对象属性或返回默认值。但是,当我尝试将其与深层嵌套的属性一起使用时,它会返回undefined。
为什么get
在这里返回undefined?我应该如何使用它来访问嵌套属性b
?
示例:
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>