访问 JS 对象中的动态嵌套键

Max*_*huk 2 javascript arrays nested object nested-documents

我有一个类似的数组['animals', 'cats', 'cute', 'fast', 'small', ...],并且想要访问对象的嵌套键,例如

let object = {
  one: {
    two: {
      three: {
        // and so on
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

通常我会写 object['animals']['cats']['cute']['fast']['small']..

问题是键和级别数是动态的(因此我可以获得具有 2 个嵌套级别或 50 个级别的对象),所以我不知道如何完成

在此先感谢您的帮助

Cer*_*nce 6

使用 迭代键数组.reduce,其中累加器是当前嵌套对象:

let object = {
  one: {
    two: {
      three: {
        prop: 'val'
      }
    }
  }
};

const props = ['one', 'two', 'three', 'prop'];
const nestedVal = props.reduce((a, prop) => a[prop], object);
console.log(nestedVal);
Run Code Online (Sandbox Code Playgroud)

要在同一点分配值,首先弹出最后一个键,使用相同的reduce技巧到达最后一个对象,并使用括号符号分配给最后一个键处的属性:

let object = {
  one: {
    two: {
      three: {
        prop: 'val'
      }
    }
  }
};

const props = ['one', 'two', 'three', 'prop'];
const lastKey = props.pop();
const nestedObj = props.reduce((a, prop) => a[prop], object);
nestedObj[lastKey] = 'newVal';
console.log(object);
Run Code Online (Sandbox Code Playgroud)