JavaScript Object获取子对象中属性的值

Pav*_*mar 0 javascript

假设我有以下对象.

{
  ...
  a: 12,
  ...
}   
Run Code Online (Sandbox Code Playgroud)

第二个对象.

{
  ...
  subOjb: {
     a: 53
  },
  ...
}   
Run Code Online (Sandbox Code Playgroud)

第三个目标.

{
  ...
  subOjb: {
     subSub: {
        a: 32
     }
  },
  ...
}
Run Code Online (Sandbox Code Playgroud)

假设我有兴趣找到属性的价值,a无论它的嵌套程度有多深.是否有一个库来获取属性的价值,无论它嵌套多深.

Cer*_*nce 6

一种选择是利用JSON.stringify,它将递归迭代所有属性,不需要库:

const obj = {
  foo: 'foo',
  outer: [
    'item',
    {
      inner: {
        prop: 'prop',
        another: {
          a: 'theValueOfA'
        }
      }
    }
  ]
};

let a;
JSON.stringify(obj, (key, val) => {
  if (key === 'a') a = val;
  return val;
});
console.log(a);
Run Code Online (Sandbox Code Playgroud)

另一种选择,编写自己的递归函数,迭代entries对象:

const obj = {
  foo: 'foo',
  outer: [
    'item',
    {
      inner: {
        prop: 'prop',
        another: {
          a: 'theValueOfA'
        }
      }
    }
  ]
};

const findProp = (obj, prop) => Object.entries(obj).reduce((a, [key, val]) => {
  if (a) return a;
  if (key === prop) return val;
  if (typeof val === 'object') return findProp(val, prop);
}, null);
console.log(findProp(obj, 'a'));
Run Code Online (Sandbox Code Playgroud)