美文网首页
JS Function -- dig

JS Function -- dig

作者: wlianfu | 来源:发表于2020-05-26 15:22 被阅读0次
const dig = (obj, target) => {
  return target in obj ? obj[target]
    : Object.values(obj).reduce((acc, val) => {
      if (acc !== undefined) return acc;
      if (typeof val === 'object') return dig(val, target);
    }, undefined);
};

const data = {
  level1: {
    level2: {
      level3: 'some data',
    },
  },
};

dig(data, 'level3');

相关文章

网友评论

      本文标题:JS Function -- dig

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