Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step
https://juejin.cn/column/7244788137410560055
2.03k stars 235 forks source link

lodash.get #20

Open Sunny-117 opened 2 years ago

Sunny-117 commented 2 years ago
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 commented 1 year ago
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 commented 1 year ago
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 commented 1 year ago
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 commented 1 year ago
  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;
    }
2. 测试
```js
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 commented 1 year ago

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 commented 1 year ago
    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 commented 1 year ago
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 commented 1 year ago
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 commented 1 year ago

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 commented 1 year ago
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 commented 1 year ago
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 commented 11 months ago
    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 commented 9 months ago
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 commented 8 months ago

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

topulikeweb commented 8 months ago
// 实现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 commented 7 months ago

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

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 commented 3 months ago
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 commented 2 months ago
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 commented 2 weeks ago
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'));