问题

实现lodash_.get,即链式调用

https://www.lodashjs.com/docs/lodash.get

答案

  1. const obj = {
  2. a: [{
  3. b: {
  4. cd: 0
  5. }
  6. }]
  7. }
  8. const v1 = this.test(obj, "a.b.cd", 100);
  9. const v2 = this.test(obj, "a[0].b.cd");
  10. const v3 = this.test(obj, ['a', '0', 'b', 'c']);
  11. const v4 = this.test(obj, ['a', '0', 'b', 'cd']);
  12. const v5 = this.test(obj, 'abc');
  13. const v6 = this.test(obj, 'a');
  14. console.log("path", v1, v2, v3, v4, v5, v6);
  1. test(obj, path, defaultValue) {
  2. let item = obj;
  3. let value = defaultValue || 'default';
  4. // 合成最终数组
  5. let arr = [];
  6. if (/\./g.test(path)) {
  7. path = path.replace(/(\.)(\w+)/g, '[$2]');
  8. path = path.replace(/^(\w+)(\[)/g,'[$1]$2');
  9. arr = path.match(/(\w+)/g)
  10. } else {
  11. if (Array.isArray(path)) {
  12. arr = path;
  13. } else {
  14. arr = [path];
  15. }
  16. }
  17. for(let i = 0; i < arr.length; i++) {
  18. if (item[arr[i]] == undefined) {
  19. break;
  20. } else {
  21. item = item[arr[i]];
  22. if (i == arr.length - 1) {
  23. value = item;
  24. }
  25. }
  26. }
  27. return value;
  28. }

image.png