美文网首页
Object FindPath

Object FindPath

作者: Ag_fronted | 来源:发表于2021-09-22 14:49 被阅读0次
const obj = {
  a: {
    a_1: {
      a_1_1: 'abc',
      a_1_2: 'efg',
    },
  },
  b: {
    b_1: 'xyz',
    b_2: '111',
  },
  c: '000',
};
function flatObj(obj, key = '', res = {}) {
  for (let [k, v] of Object.entries(obj)) {
    if (typeof v === 'object') {
      flatObj(v, key + k + '.', res);
    } else {
      res[key + k] = v;
    }
  }
  return res;
}

function findPath(obj, value) {
  let o = flatObj(obj);
  for (let i in o) {
    if (o[i] === value) {
      return i.split('.');
    }
  }
  return [];
}
console.log(findPath(obj, 'xyz')); // ['b', 'b_1']

相关文章

网友评论

      本文标题:Object FindPath

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