面试遇到的题目,记录一哈,简易实现 lodash 方法

原题目,其实和实现 _get 方法没啥区别,实现思路不同而已


题目:
现有 Json 数据,格式如下:
json = { "a": [ { "b": "c" } , ... ] , ... }; 请实现一个方法:get(json, "a[0].b"),使其返回值为 c。 要求:自己实现遍历逻辑,不允许使用正则表达式、不允许使用 eval()等类似 方法。
测试用例:
json = { "a": [ { "b": "c" }, "d" ], "x": 1} get(json, "a[0].b") == "c"
get(json, "a[1]") == "d"
get(json, "x") == 1

原题解就不献丑啦~

  const str2path = (path) => {
const reg = /[^.[\]]/g
let result = []
// const rePropName = /[^.[\]]+|\[(?:([^"'][^[]*)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g
path.replace(reg, function (key) {
if (key) {
result.push(key.trim())
}
})
return result
}

const get = (obj, path) => {
const basePath = str2path(path);
let index = 0;

while (obj !== null && index < basePath.length) {
obj = obj[basePath[index ++]];
}

return obj;
}

const obj = {
a: {
b: {
c: 1
}
}
}

get(obj, 'a[b].c') // 1