Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

lodash.get

Sunny-117 opened this issue · comments

const obj = {
    a: {
        b: 123
    },
    arr: [
        {
            demo: 'demo'
        }
    ]
}
function getKey(obj, str) {
   
}
console.log(getKey(obj, 'a.b'));
console.log(getKey(obj, 'arr[0].demo'));
function _get(obj,path,defaultValue="undefined"){
  //先将path处理成统一格式
  let newPath = [];
  if(Array.isArray(path)){
    newPath = path;
  }
  else{
    // 字符串类型 obj[a] obj.a  这里把'[' 替换成'.' ']' 替换成''
    newPath = path.replace(/\[/g,'.').replace(/\]/g,'').split('.');//最后转成数组
    console.log(newPath);
  }
  //obj 替换成 obj.a 逐步调用
  return newPath.reduce((o,k) => {
    return (o || {})[k]; 
  },obj) || defaultValue
};

var object = { 'a': [{ 'b': { 'c': 3 } }] };
 
console.log(_get(object, 'a[0].b.c'));;
// => 3
 
console.log(_get(object, ['a', '0', 'b', 'c']));;
// => 3
 
console.log(_get(object, 'a.b.c', 'default'));;
// => 'default'
const obj = {
	a: {
		b: 123,
	},
	arr: [
		{
			demo: "demo",
		},
	],
};
function getKey(obj, path, defaltVal) {
	str = str.replace(/\[[\d+]\]/g, (match) => {
		return "." + match.slice(1, match.length - 1);
	});
	const arr = str.split(".");
	try {
		for (const item of arr) {
			obj = obj[item];
		}
	} finally{
        // 如果第二个参数格式错误, obj为undefined
        if(obj){
            return obj
        }
        return defaltVal
    }
}
console.log(getKey(obj, "a.b", "err"));
console.log(getKey(obj, "arr[0].demo", "err"));
console.log(getKey(obj, "arr[1].demo", "err"));
commented
var object = { 'a': [{ 'b': { 'c': 3 } }] };
 
console.log(_get(object, 'a[0].b.c'));
// => 3
console.log(_get(object, ['a', '0', 'b', 'c']));
// => 3
console.log(_get(object, 'a.b.c', 'default')); // 第三个参数如果值是undefined,则返回第三个参数
// => 'default'

/**
 * 
 * @param {*} object
 * @param {*} key [] | string
 * @param {*} value 如果值是undefined,则返回第三个参数
 */
function _get(object, key, value) {
    if(!Array.isArray(key)) {
        key = key.trim().replace(/\[(.*)\]/g, (match, i) => {
            return `.${i}`;
        }).split('.')
    }
    for(let i = 0; i < key.length; i++) {
        object = object[key[i]];
        if(!object) return value;
    }
    return object | value;
}
  1. 实现
function get(source, path, defaultValue = undefined) {
  const paths = path
    .repalce(/\[(\w+)\]/g, ".$1")
    .repalce(/\['(\w+)'\]/g)
    .repalce(/\["(\w+)"\]/g)
    .split(".");
  let result = source;
  for (const p of path) {
    result = result?.p;
  }
  return result === undefined ? defaultValue : result;
}
  1. 测试
const object = { a: [{ b: { c: 3 } }] };

get(object, “a[0].b.c”); //=> 3

get(object, ‘a[0][“b”][“c”]); //=> 3

get(object, “a[100].b.c”, 10086);//=> 10086
function getKey(obj, str) {
  if (/\[/g.test(str)) {
    str = str.replaceAll(/\[/g, '.').replaceAll(/\]/g, '')
  }
  const keyArr = str.split('.')
  for (const k of keyArr) {
    obj = obj[k]
  }
  return obj
}
commented
    const obj = {
        a: {
            b: 123
        },
        arr: [
            {
                demo: 'demo'
            }
        ]
    }
    function getKey(obj, str, defaultValue = undefined) {
        str = str.replace(/\[/g, '.').replace(/\]/g, '.');
        const arr = str.split('.');
        for (let k of arr) {
            if (obj == undefined) return defaultValue;
            obj = obj[k];
        }
        if (obj == undefined) return defaultValue;
        return obj;
    }
    console.log(getKey(obj, 'a.b'));
    console.log(getKey(obj, 'arr[0].demo'));
var object = { 'a': [{ 'b': { 'c': 3 } }] };

function getKey (obj, str, defaultValue) {
  let path;
  if (Array.isArray(str)) {
    path = str
  } else {
    str = str.replace(/\[/g, '.').replace(/\]/g, '')
    path = str.split('.')
  }

  let res = obj
  path.forEach((value) => {
    res = res?.[value]
  })
  return res ?? defaultValue
}

console.log(getKey(object, 'a[0].b.c'));
// => 3

console.log(getKey(object, ['a', '0', 'b', 'c']));
// => 3

console.log(getKey(object, 'a.b.c', 'default'));
// => undefined
commented
var object = { 'a': [{ 'b': { 'c': 3 } }] };

function getKey(obj, path, defaultValue) {
  const keys = Array.isArray(path) ? path : path.split(/[.\[\]]+/g)
  for (const key of keys) {
	if (obj === undefined) {
	  return defaultValue
	}
	obj = obj[key]
  }
  return obj
}
getKey(object, 'a[0].b.c')
getKey(object, ['a', '0', 'b'])
getKey(object, 'a.b.c', 'default')
commented

function get(data, str) { str = str.replace(/\[\d+\]/g, (match) => { return.${match.slice(1, match.length - 1)}; }); console.log(str); let keys = str.split("."); for (let i = 0; i < keys.length; i++) { data = data[keys[i]]; } return data; } const obj = { a: { b: 123, c: { d: 111, }, }, arr: [ { demo: "demo", }, ], }; // console.log(get(obj, "a.b")); console.log(get(obj, "arr[0]"));

function get(obj, path, defaultValue='undefined') {
    const pathArr = split('.');
    let curObj = obj;
    
    for (let i=0; i<pathArr.length; i++) {
        if (!curObj || Object.prototype.toString(curObj) !== "[object Object]") {
            return defaultValue;
        }
        
        curObj = curObj[pathArr[i]]; 
    }
    
    return curObj ? curObj : defaultValue;
}
function lodashGet(obj, path, defaultValue = void 0){
  let newPath = Array.isArray(path) ? path : path.split(/[.\[\]]/).filter(Boolean);

  return newPath.reduce((prev, curr)=> {
    return (prev || {})[curr]
  }, obj) || defaultValue
}

const obj = {
  a: {
      b: 123
  },
  arr: [
      {
          demo: 'demo'
      }
  ]
}

console.log(lodashGet(obj,'arr[0].demo'));
    function getKey(obj, pathStr) {
      if (!obj) return
      if (typeof obj !== 'object') return

      pathStr = pathStr.replace(/(\w+)\[(\d+)\]/, '$1.$2')
      const paths = pathStr.split('.')

      let ans = obj
      let index = 0
      while (ans && index < paths.length) {
        ans = ans[paths[index]]
        index++
      }

      return ans
    }
function myGet(targetObj, path, defaultValue) {
  let result
  if (typeof path === 'string') {
    path = path.split(/\.|\[|\]/).filter(Boolean)
  }

  result = path.reduce((pre, cur) => {
    if (pre && pre[cur]) {
      return pre[cur]
    }
    return undefined
  }, targetObj)

  return result || defaultValue
}

/************** TEST **************/
let object = { a: [{ b: { c: 3 } }] }

console.log(myGet(object, 'a[0].b.c'))
// => 3

console.log(myGet(object, ['a', '0', 'b', 'c']))
// => 3

console.log(myGet(object, 'a.b.c', 'default'))
// => 'default'
commented

function get(obj,attr){
const attrArr = attr.split('.')
let res=obj
attrArr.forEach(item=>{
res = res[item]
})
return res
}

// 实现lodash.get

const obj = {
  a: {
    b: 123
  },
  arr: [
    {
      demo: 'demo'
    }
  ]
}

function getKey (obj, str) {
  let res = obj
  let arr = Array.isArray(str) ? str : str.split('.')
  
  for (let i = 0; i < arr.length; i++) {
    let keys = arr[i].split('[')
    if (keys.length === 1) {
      res = res[keys[0]]
    } else {
      let index = parseInt(keys[1].slice(0, -1))
      res = res[keys[0]][index]
    }
  }
  return res
}

console.log(getKey(obj, 'a.b'));
console.log(getKey(obj, 'arr[0].demo'));
commented

用栈来找到 [ ] 以及 . . 之间的内容

function getKeys(path) {
    let start = 0;
    let first = 0;
    const keys = [];
    for(let i=0;i<path.length;i++) {
        if (path[i] === '[' || (path[i] === '.' && start === 0)) {
            start = i;
            if (first === 0) {
                keys.push(path.slice(0, i));
                first = 1;
            }
            continue;
        }
        if (path[i] === ']') {
            keys.push(path.slice(start + 1, i))
            start = 0;
            continue;
        }
        if (path[i] === '.' && start) {
            keys.push(path.slice(start + 1, i));
            start = i;
            continue;
        }
    }
    
    if (start) {
        keys.push(path.slice(start + 1, path.length))
    }
    return keys
}
const obj = {
    a: {
        b: 123
    },
    arr: [
        {
            demo: 'demo'
        }
    ]
}
function getKey(obj, str, defaultVal) {
    const keys = getKeys(str);
    const result = keys.reduce((acc, key) => {
        if (acc === undefined) return undefined;
        return acc[key];
    }, obj);
    if (result === undefined) return defaultVal;
    return result;
}
console.log(getKey(obj, 'a.b'));
console.log(getKey(obj, 'arr[0].demo'));
console.log(getKey(obj, 'arr[0].demo.a.b'));