美文网首页
算法练习04 取对象的深层属性

算法练习04 取对象的深层属性

作者: 多啦斯基周 | 来源:发表于2018-11-19 11:51 被阅读0次

题目(2018-11-19)

有时候我们需要访问一个对象较深的层次,但是如果这个对象某个属性不存在的话就会报错,例如:

var data = { a: { b: { c: 'ScriptOJ' } } }
data.a.b.c // => scriptoj
data.a.b.c.d // => 报错,代码停止执行
console.log('ScriptOJ') // => 不会被执行

请你完成一个safeGet函数,可以安全的获取无限多层次的数据,一旦数据不存在不会报错,会返回undefined,例如:

var data = { a: { b: { c: 'ScriptOJ' } } }
safeGet(data, 'a.b.c') // => scriptoj
safeGet(data, 'a.b.c.d') // => 返回 undefined
safeGet(data, 'a.b.c.d.e.f.g') // => 返回 undefined
console.log('ScriptOJ') // => 打印 ScriptOJ

实现

循环

首先想到的方法就是利用循环实现,每次循环都进行一次判断,判断属性是否存在,存在继续,不存在跳出

最早完成的代码:

const safeGet = (data, path) => {
  let result = undefined;
  if (!data || !path) {
    return result
  }
  const tempArr = path.split('.');
  for (let i = 0; i < tempArr.length; i++) {
    const key = tempArr[i];
    if (data[key]) {
      result = data[key];
      data = data[key];
    } else {
      result = undefined;
      break;
    }
  }
  return result;
};

这段代码至少有两个可以优化的地方:

  1. 没有必要声明result这个变量,直接使用data即可
  2. for循环内部不必break,直接return跳出函数即可

所以优化之后:

const safeGet = (data, path) => {
  if (!data || !path) {
    return undefined
  }
  const tempArr = path.split('.');
  for (let i = 0; i < tempArr.length; i++) {
    const key = tempArr[i];
    if (data[key]) {
      data = data[key];
    } else {
      return undefined;
    }
  }
  return data;
};

递归

除了使用循环,当然也可以递归调用函数来实现:

const safeGet = (data, path) => {
  const key = path.split('.')[0];
  const restPath = path.slice(2);
  if (!data[key]) {
    return undefined;
  }
  if (!restPath) {
    return data[key]
  }
  return safeGet(data[key], restPath)
};

try...catch

看看了讨论区,受了一些启发,还可以使用try...catch实现

const safeGet = (data, path) => {
  const tempArr = path.split('.');
  try {
    while (tempArr.length > 0) {
      data = data[tempArr.shift()]
    }
    return data;
  } catch (e) {
    return undefined;
  }
};

reduce

还可以使用ES6中强大的reduce实现,非常简洁:

const safeGet = (data, path) => {
  if (!data || !path) {
    return undefined
  }
  const tempArr = path.split('.');
  // 注意初始值是给谁赋值
  return tempArr.reduce((total, current) = > {
    return (total && total[current]) ? total[current] : undefined
  }, data)
};

要注意的一点,

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

参数initialValue是初始值,是赋值给total的值,不要搞错。

参考

相关文章

网友评论

      本文标题:算法练习04 取对象的深层属性

      本文链接:https://www.haomeiwen.com/subject/blvofqtx.html