Skip to content

Commit c6e07d3

Browse files
Update 0011. Get.md
1 parent 11e7df7 commit c6e07d3

File tree

1 file changed

+19
-14
lines changed

1 file changed

+19
-14
lines changed

JS-Core/0011. Get.md

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,25 @@
33
<img width="710" alt="Screen Shot 2023-05-09 at 11 57 21 PM" src="https://github.com/cheatsheet1999/FrontEndCollection/assets/37787994/96e7e5bf-2f2c-4783-a089-2491b2d0f9bb">
44

55
```js
6-
function get(obj, path, defaultValue) {
7-
if (typeof path === 'string') {
8-
path = path.split('.');
9-
}
10-
11-
let result = obj;
12-
for (let key of path) {
13-
if (typeof result !== 'object' || result === null || !result.hasOwnProperty(key)) {
14-
return defaultValue;
15-
}
16-
result = result[key];
17-
}
18-
return result;
19-
}
6+
/**
7+
* @param {Object} objectParam
8+
* @param {string|Array<string>} pathParam
9+
* @param {*} [defaultValue]
10+
* @return {*}
11+
*/
12+
export default function get(objectParam, pathParam, defaultValue) {
13+
if (typeof pathParam === 'string') {
14+
pathParam = pathParam.split('.');
15+
}
16+
17+
for (let key of pathParam) {
18+
if (typeof objectParam !== 'object' || objectParam === null || !objectParam.hasOwnProperty(key)) {
19+
return defaultValue;
20+
}
21+
objectParam = objectParam[key];
22+
}
23+
return objectParam;
24+
}
2025
```
2126

2227
## Test Cases

0 commit comments

Comments
 (0)