Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lodash.get #20

Open
Sunny-117 opened this issue Nov 3, 2022 · 19 comments
Open

lodash.get #20

Sunny-117 opened this issue Nov 3, 2022 · 19 comments

Comments

@Sunny-117
Copy link
Owner

Sunny-117 commented Nov 3, 2022

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'));
@lxy-Jason
Copy link
Contributor

lxy-Jason commented Nov 27, 2022

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'

@veneno-o
Copy link
Contributor

veneno-o commented Jan 16, 2023

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"));

@zzyyhh22lx
Copy link

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;
}

@kangkang123269
Copy link

kangkang123269 commented Feb 20, 2023

  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

@sv-98-maxin
Copy link

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
}

@xun-zi
Copy link

xun-zi commented Mar 13, 2023

    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'));

@Little-Bla-ck
Copy link

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

@quitone
Copy link

quitone commented May 14, 2023

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')

@cscty
Copy link

cscty commented Jun 17, 2023

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]"));

@HangHZhang
Copy link

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;
}

@Liu6625
Copy link

Liu6625 commented Oct 23, 2023

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'));

@AAA611
Copy link

AAA611 commented Dec 19, 2023

    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
    }

@zz8023wanjin
Copy link

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'

@Aoda57
Copy link

Aoda57 commented Mar 6, 2024

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

@topulikeweb
Copy link

// 实现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'));

@pbgf
Copy link

pbgf commented Apr 12, 2024

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

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'));

@skyler-developer
Copy link

function _get(obj, path, defaultValue) {
    if (!Array.isArray(path)) {
        path = path.replace(/\[/g, ".").replace(/\]/g, "").split(".");
    }
    return (
        path.reduce((a, b) => {
            return (a || {})[b];
        }, obj) || String(defaultValue)
    );
}

@iamzwq
Copy link

iamzwq commented Aug 28, 2024

function get(obj, path, defaultValue) {
  if (!Array.isArray(path)) {
    path = path.match(/[^.[\]]+/g) || [];
  }
  for (const key of path) {
    if (!obj[key]) {
      return defaultValue;
    }
    obj = obj[key];
  }
  return obj === undefined ? defaultValue : obj;
}

@Windseek
Copy link

Windseek commented Nov 6, 2024

const obj = {
  a: {
      b: 123
  },
  arr: [
      {
          demo: 'demo'
      }
  ]
}
function getKey(obj, str) {
  let arr = str.replace(/\[/g, '.').replace(/\]/g, '').split('.');
  return arr.reduce((pre, cur) => {
    return (pre||{})[cur]||'';
  },obj)
}
console.log(getKey(obj, 'a.b'));
console.log(getKey(obj, 'arr[0].demo'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests